对列表使用 Python 字符串格式
我在 Python 2.6.5 中构造了一个字符串 s
,它将具有不同数量的 %s
标记,这些标记与列表 x
中的条目数量相匹配>。我需要写出一个格式化的字符串。以下内容不起作用,但表明了我正在尝试做的事情。在此示例中,有三个 %s
标记,并且列表具有三个条目。
s = '%s BLAH %s FOO %s BAR'
x = ['1', '2', '3']
print s % (x)
我希望输出字符串为:
1 BLAH 2 FOO 3 BAR
I construct a string s
in Python 2.6.5 which will have a varying number of %s
tokens, which match the number of entries in list x
. I need to write out a formatted string. The following doesn't work, but indicates what I'm trying to do. In this example, there are three %s
tokens and the list has three entries.
s = '%s BLAH %s FOO %s BAR'
x = ['1', '2', '3']
print s % (x)
I'd like the output string to be:
1 BLAH 2 FOO 3 BAR
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您应该查看 python 的 format 方法。然后您可以像这样定义格式化字符串:
You should take a look to the format method of python. You could then define your formatting string like this :
而不是
instead of
在这个资源页面之后,如果 x 的长度不同,我们可以使用
:为列表 x 中的每个元素创建一个占位符。这是示例:
Following this resource page, if the length of x is varying, we can use:
to create a place holder for each element from the list
x
. Here is the example:这是单行。使用 print() 的格式来迭代列表的一点即兴答案。
这个怎么样(python 3.x):
阅读这里有关使用 format()。
Here is a one liner. A little improvised answer using format with print() to iterate a list.
How about this (python 3.x):
Read the docs here on using format().
因为我刚刚了解了这个很酷的事情(从格式字符串中索引到列表),所以我添加了这个老问题。
输出:
但是,我仍然不知道如何进行切片(在格式字符串
'"{x[2:4]}".format...
内部),并且很乐意如果有人有想法就弄清楚,但我怀疑你根本无法做到这一点。Since I just learned about this cool thing(indexing into lists from within a format string) I'm adding to this old question.
Output:
However, I still haven't figured out how to do slicing(inside of the format string
'"{x[2:4]}".format...
,) and would love to figure it out if anyone has an idea, however I suspect that you simply cannot do that.这是一个有趣的问题!对于可变长度列表处理此问题的另一种方法是构建一个充分利用
.format
方法和列表解包的函数。在下面的示例中,我没有使用任何花哨的格式,但可以轻松更改以满足您的需求。This was a fun question! Another way to handle this for variable length lists is to build a function that takes full advantage of the
.format
method and list unpacking. In the following example I don't use any fancy formatting, but that can easily be changed to suit your needs.如果只是将任意值列表填充到字符串中,您可以执行以下操作,这与 @neobot 的答案相同,但更现代和简洁。
如果您连接在一起的已经是某种结构化数据,我认为最好做一些类似的事情:
For just filling in an arbitrary list of values to a string, you could do the following, which is the same as @neobot's answer but a little more modern and succinct.
If what you are concatenating together is already some kind of structured data, I think it would be better to do something more like:
输出是
The output is