Printing tuple with string formatting in Python

前端 未结 14 2351
情话喂你
情话喂你 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 03:57
    >>> tup = (1, 2, 3)
    >>> print "Here it is: %s" % (tup,)
    Here it is: (1, 2, 3)
    >>>
    

    Note that (tup,) is a tuple containing a tuple. The outer tuple is the argument to the % operator. The inner tuple is its content, which is actually printed.

    (tup) is an expression in brackets, which when evaluated results in tup.

    (tup,) with the trailing comma is a tuple, which contains tup as is only member.

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

    You can try this one as well;

    tup = (1,2,3)
    print("this is a tuple {something}".format(something=tup))
    

    You can't use %something with (tup) just because of packing and unpacking concept with tuple.

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

    Note that the % syntax is obsolete. Use str.format, which is simpler and more readable:

    t = 1,2,3
    print 'This is a tuple {0}'.format(t)
    
    0 讨论(0)
  • 2020-11-28 04:01

    For python 3

    tup = (1,2,3)
    print("this is a tuple %s" % str(tup))
    
    0 讨论(0)
  • 2020-11-28 04:02

    Talk is cheap, show you the code:

    >>> tup = (10, 20, 30)
    >>> i = 50
    >>> print '%d      %s'%(i,tup)
    50  (10, 20, 30)
    >>> print '%s'%(tup,)
    (10, 20, 30)
    >>> 
    
    0 讨论(0)
  • 2020-11-28 04:04
    t = (1, 2, 3)
    
    # the comma (,) concatenates the strings and adds a space
    print "this is a tuple", (t)
    
    # format is the most flexible way to do string formatting
    print "this is a tuple {0}".format(t)
    
    # classic string formatting
    # I use it only when working with older Python versions
    print "this is a tuple %s" % repr(t)
    print "this is a tuple %s" % str(t)
    
    0 讨论(0)
提交回复
热议问题