Printing tuple with string formatting in Python

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

    Try this to get an answer:

    >>>d = ('1', '2') 
    >>> print("Value: %s" %(d))
    Traceback (most recent call last):
      File "", line 1, in 
    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.

提交回复
热议问题