[英]Printing formatted tuple values
这可能是最简单的问题。 但我尝试以下列方式打印元组的各个值。
mytuple=('new','lets python','python 2.7')
>>> print "%{0} experience, %{1} with %{2} " %mytuple
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
print "%{0} experience, %{1} with %{2} " %mytuple
ValueError: unsupported format character '{' (0x7b) at index 1
我想打印输出如下所示。
"new experience, lets python with python 2.7"
我不记得它在哪里完成。 它被称为解包元组值,打印格式化元组。
而不是混合printf
style格式和str.format
,选择一个:
>>> mytuple = ('new','lets python','python 2.7')
>>> print "%s experience, %s with %s" % mytuple
new experience, lets python with python 2.7
>>> print "{0} experience, {1} with {2}".format(*mytuple)
new experience, lets python with python 2.7
您可以使用格式方法和星号来解决问题。
有关详细信息,请参阅此链接
>>mytuple=('new','lets python','python 2.7')
>>print "{0} experience, {1} with {2} ".format(*mytuple)
new experience, lets python with python 2.7
你可以任何一种方法。 然而,格式更简单,您可以更轻松地管理它。
>>> a = '{0} HI {1}, Wassup {2}'
>>> a.format('a', 'b', 'c')
'a HI b, Wassup c'
>>> b = ('a' , 'f', 'g')
>>> a.format(*b)
'a HI f, Wassup g'
你刚刚混合了printf
和str.format
,你需要选择其中一个:
>>> tuple1 = ("hello", "world", "helloworld")
>>> print("%s, %s, %s" % tuple1)
要么:
>>> tuple1 = ("hello", "world", "helloworld")
>>> print("{}, {}, {}".format(*tuple1))
只需稍微修改一下:
>>> mytuple=('new','lets python','python 2.7')
>>> print "%s experience, %s with %s " %mytuple
new experience, lets python with python 2.7
>>>
我遇到了元组格式化的问题,并找到了解决方案:
mydate =(9,1)print(“日期是({date [0]},{date [1]})”。format(date = mydate))日期是(9,1)
(似乎解决方案仅针对一些问题,我们知道固定元组。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.