首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >打印格式化元组值

打印格式化元组值
EN

Stack Overflow用户
提问于 2016-05-16 02:16:30
回答 6查看 3K关注 0票数 2

这可能是最简单的问题。但我尝试以下列方式打印元组的单个值。

代码语言:javascript
运行
复制
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

我想打印输出如下所示。

代码语言:javascript
运行
复制
"new experience, lets python with python 2.7"

我不记得它是在哪里做的。它叫解包元组值,打印格式的元组。

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2016-05-16 02:21:18

与其将printf-style格式化和str.format混合,选择一个:

-style格式

代码语言:javascript
运行
复制
>>> 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)">str.format

代码语言:javascript
运行
复制
>>> print "{0} experience, {1} with {2}".format(*mytuple)
new experience, lets python with python 2.7
票数 5
EN

Stack Overflow用户

发布于 2016-05-16 02:27:57

您可以使用格式方法和星号来解决这个问题。

详情请参阅此链接

代码语言:javascript
运行
复制
>>mytuple=('new','lets python','python 2.7')
>>print "{0} experience, {1} with {2} ".format(*mytuple)
new experience, lets python with python 2.7 
票数 1
EN

Stack Overflow用户

发布于 2016-05-16 02:29:39

你可以用任何一种方法。然而,格式的事情更简单,您可以更容易地管理它。

代码语言:javascript
运行
复制
>>> 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'
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37245791

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档