问题:将Python字符串格式化与列表一起使用
我s在Python 2.6.5中构造了一个字符串,该字符串将具有不同数量的%s令牌,这些令牌与list中的条目数匹配x。我需要写出格式化的字符串。以下内容不起作用,但表示我要执行的操作。在此示例中,有三个%s标记,并且列表具有三个条目。
s = '%s BLAH %s FOO %s BAR'
x = ['1', '2', '3']
print s % (x)我希望输出字符串为:
1 BLAH 2 FOO 3 BAR
回答 0
print s % tuple(x)代替
print s % (x)回答 1
您应该看一下python 的format方法。然后,您可以像这样定义格式字符串:
>>> s = '{0} BLAH BLAH {1} BLAH {2} BLAH BLIH BLEH'
>>> x = ['1', '2', '3']
>>> print s.format(*x)
'1 BLAH BLAH 2 BLAH 3 BLAH BLIH BLEH'回答 2
在此资源页面之后,如果x的长度变化,我们可以使用:
', '.join(['%.2f']*len(x))为列表中的每个元素创建一个占位符x。这是示例:
x = [1/3.0, 1/6.0, 0.678]
s = ("elements in the list are ["+', '.join(['%.2f']*len(x))+"]") % tuple(x)
print s
>>> elements in the list are [0.33, 0.17, 0.68]回答 3
这是一行代码。一个临时的答案,使用带有print()的format来迭代列表。
怎么样(Python 3.x):
sample_list = ['cat', 'dog', 'bunny', 'pig']
print("Your list of animals are: {}, {}, {} and {}".format(*sample_list))在此处阅读有关使用format()的文档。
回答 4
由于我刚刚学到了这个很酷的东西(从格式字符串中索引到列表中),所以我添加了这个老问题。
s = '{x[0]} BLAH {x[1]} FOO {x[2]} BAR'
x = ['1', '2', '3']
print (s.format (x=x))输出:
1 BLAH 2 FOO 3 BAR但是,我仍然没有弄清楚如何进行切片(在格式字符串'"{x[2:4]}".format...中),并且很想弄清楚是否有人有想法,但是我怀疑您根本无法做到这一点。
回答 5
这是一个有趣的问题!处理可变长度列表的另一种方法是构建一个充分利用该.format方法和列表拆包的功能。在下面的示例中,我不使用任何特殊的格式,但是可以轻松地对其进行更改以满足您的需求。
list_1 = [1,2,3,4,5,6]
list_2 = [1,2,3,4,5,6,7,8]
# Create a function that can apply formatting to lists of any length:
def ListToFormattedString(alist):
    # Create a format spec for each item in the input `alist`.
    # E.g., each item will be right-adjusted, field width=3.
    format_list = ['{:>3}' for item in alist] 
    # Now join the format specs into a single string:
    # E.g., '{:>3}, {:>3}, {:>3}' if the input list has 3 items.
    s = ','.join(format_list)
    # Now unpack the input list `alist` into the format string. Done!
    return s.format(*alist)
# Example output:
>>>ListToFormattedString(list_1)
'  1,  2,  3,  4,  5,  6'
>>>ListToFormattedString(list_2)
'  1,  2,  3,  4,  5,  6,  7,  8'回答 6
与@neobot的答案相同,但更加现代和简洁。
>>> l = range(5)
>>> " & ".join(["{}"]*len(l)).format(*l)
'0 & 1 & 2 & 3 & 4'回答 7
x = ['1', '2', '3']
s = f"{x[0]} BLAH {x[1]} FOO {x[2]} BAR"
print(s)输出是
1 BLAH 2 FOO 3 BAR
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

