Printing tuple with string formatting in Python

前端 未结 14 2495
情话喂你
情话喂你 2020-11-28 03:19

So, i have this problem. I got tuple (1,2,3) which i should print with string formatting. eg.

tup = (1,2,3)
print \"this is a tuple %something\" % (tup)
         


        
14条回答
  •  伪装坚强ぢ
    2020-11-28 04:18

    Please note a trailing comma will be added if the tuple only has one item. e.g:

    t = (1,)
    print 'this is a tuple {}'.format(t)
    

    and you'll get:

    'this is a tuple (1,)'
    

    in some cases e.g. you want to get a quoted list to be used in mysql query string like

    SELECT name FROM students WHERE name IN ('Tom', 'Jerry');
    

    you need to consider to remove the tailing comma use replace(',)', ')') after formatting because it's possible that the tuple has only 1 item like ('Tom',), so the tailing comma needs to be removed:

    query_string = 'SELECT name FROM students WHERE name IN {}'.format(t).replace(',)', ')')
    

    Please suggest if you have decent way of removing this comma in the output.

提交回复
热议问题