使用带有列表的Python字符串格式

时间:2011-09-27 11:51:03

标签: python string list formatting string-formatting

我在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

8 个答案:

答案 0 :(得分:127)

你应该看一下python的format方法。然后,您可以像这样定义格式字符串:

>>> s = '{0} BLAH {1} BLAH BLAH {2} BLAH BLAH BLAH'
>>> x = ['1', '2', '3']
>>> print s.format(*x)
'1 BLAH 2 BLAH BLAH 3 BLAH BLAH BLAH'

答案 1 :(得分:99)

print s % tuple(x)

而不是

print s % (x)

答案 2 :(得分:22)

resource page之后,如果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 :(得分:15)

因为我刚刚了解了这个很酷的东西(从格式字符串中索引到列表)我添加了这个老问题。

s = '{x[0]} BLAH {x[1]} FOO {x[2]} BAR'
x = ['1', '2', '3']
print s.format (x=x)

然而,我仍然没有想出如何进行切片(在格式字符串'"{x[2:4]}".format...内部),如果有人有想法,我很想弄明白,但我怀疑你只是不能这样做。

答案 4 :(得分:9)

这是一个有趣的问题!另一种处理用于可变长度列表的方法是构建一个充分利用.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'

答案 5 :(得分:8)

这是一行。在列表中使用print()格式的简单回答。

这个怎么样:(python 3.x)

# STEP 1 - upload image
file = open(IMAGE_PATH, 'rb')
data = file.read()
r = api.request('media/upload', None, {'media': data})
print('UPLOAD MEDIA SUCCESS' if r.status_code == 200 else 'UPLOAD MEDIA FAILURE')

# STEP 2 - post tweet with a reference to uploaded image
if r.status_code == 200:
    media_id = r.json()['media_id']
    r = api.request(
        'statuses/update', {'status': TWEET_TEXT, 'media_ids': media_id})
    print('UPDATE STATUS SUCCESS' if r.status_code == 200 else 'UPDATE STATUS FAILURE')

使用format阅读此处的文档。

答案 6 :(得分:3)

与@neobot的答案相同,但更加现代和简洁。

>>> l = range(5)
>>> " & ".join(["{}"]*len(l)).format(*l)
'0 & 1 & 2 & 3 & 4'

答案 7 :(得分:0)

x = ['1', '2', '3']
s = f"{x[0]} BLAH {x[1]} FOO {x[2]} BAR"
print(s)

输出为

1 BLAH 2 FOO 3 BAR