Printing tuple with string formatting in Python

前端 未结 14 2340
情话喂你
情话喂你 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.

    0 讨论(0)
  • 2020-11-28 04:18

    Try this to get an answer:

    >>>d = ('1', '2') 
    >>> print("Value: %s" %(d))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: not all arguments converted during string formatting
    

    If we put only-one tuple inside (), it makes a tuple itself:

    >>> (d)
    ('1', '2')
    

    This means the above print statement will look like: print("Value: %s" %('1', '2')) which is an error!

    Hence:

    >>> (d,)
    (('1', '2'),)
    >>> 
    

    Above will be fed correctly to the print's arguments.

    0 讨论(0)
提交回复
热议问题