我在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
我在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
你应该查看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'
%
运算符只能解包元组。 - patryss
的构建变得更加复杂,因为我需要包含递增数字而不仅仅是每个位置的%s
。 s
以多种不同的步骤构建,所以只包含%s
标记更容易。 - SabreWolfyprint u'%(blah)d BLAHS %(foo)d FOOS …' % {'blah': 15, 'foo': 4}
。 - patryss = '{} BLAH {} BLAH BLAH {} BLAH BLAH BLAH'
。 - Dennis Williamsonprint s % tuple(x)
用...代替
print s % (x)
(x)
与x
是相同的。在Python中,将单个标记放在括号中没有任何意义。通常在foo = (bar,)
中加括号可以使其更易于阅读,但是foo = bar,
完全具有相同的功能。 - patrysfoo = (bar, )
:) - patrys.format()
更简单、更短,而后者不应该成为得票最高的答案!! - Apostolos根据此资源页面,如果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]
以下是一个Python 3.x的示例:
sample_list = ['cat', 'dog', 'bunny', 'pig']
print("Your list of animals are: {}, {}, {} and {}".format(*sample_list))
在这里阅读有关使用format()的文档。
由于我刚学到这个很酷的东西(在格式化字符串内对列表进行索引),所以我正在为这个旧问题添加内容。
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...
),如果有人有想法,我很愿意弄清楚,但是我怀疑您可能无法这样做。
这是一个有趣的问题!处理可变长度列表的另一种方法是构建一个函数,充分利用 .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'
如果只是想将任意值填充到字符串列表中,可以使用以下方法,与@neobot的答案相同但更为现代且简洁。
>>> l = range(5)
>>> " & ".join(["{}"]*len(l)).format(*l)
'0 & 1 & 2 & 3 & 4'
>>> data = {"blah": 1, "foo": 2, "bar": 3}
>>> " ".join([f"{k} {v}" for k, v in data.items()])
'blah 1 foo 2 bar 3'
x = ['1', '2', '3']
s = f"{x[0]} BLAH {x[1]} FOO {x[2]} BAR"
print(s)
输出结果为
1 BLAH 2 FOO 3 BAR