Printing tuple with string formatting in Python

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

    Even though this question is quite old and has many different answers, I'd still like to add the imho most "pythonic" and also readable/concise answer.

    Since the general tuple printing method is already shown correctly by Antimony, this is an addition for printing each element in a tuple separately, as Fong Kah Chun has shown correctly with the %s syntax.

    Interestingly it has been only mentioned in a comment, but using an asterisk operator to unpack the tuple yields full flexibility and readability using the str.format method when printing tuple elements separately.

    tup = (1, 2, 3)
    print('Element(s) of the tuple: One {0}, two {1}, three {2}'.format(*tup))
    

    This also avoids printing a trailing comma when printing a single-element tuple, as circumvented by Jacob CUI with replace. (Even though imho the trailing comma representation is correct if wanting to preserve the type representation when printing):

    tup = (1, )
    print('Element(s) of the tuple: One {0}'.format(*tup))
    

提交回复
热议问题