Sab*_*lfy 95 python string formatting list string-formatting
我s在Python 2.6.5中构造了一个字符串,它将具有不同数量的%s标记,这些标记与列表中的条目数相匹配x.我需要写出一个格式化的字符串.以下不起作用,但表明我正在尝试做什么.在此示例中,有三个%s令牌,列表有三个令牌.
s = '%s BLAH %s FOO %s BAR'
x = ['1', '2', '3']
print s % (x)
我想输出字符串是:
1 BLAH 2 FOO 3 BAR
Céd*_*ien 138
你应该看一下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'
inf*_*red 103
print s % tuple(x)
代替
print s % (x)
neo*_*bot 26
在此资源页面之后,如果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]
Jor*_*ley 17
因为我刚学会了这个很酷的东西(从格式字符串中索引到列表)我正在添加这个老问题.
s = '{x[0]} BLAH {x[1]} FOO {x[2]} BAR'
x = ['1', '2', '3']
print s.format (x=x)
但是,我仍然没有想出如何进行切片(在格式字符串内部'"{x[2:4]}".format...),如果有人有想法,我很想弄明白,但我怀疑你根本不能这样做.
gee*_*rsh 13
这是在列表中使用print()格式的一个简单的临时答案.
怎么样:(py3)
sample_list = ['cat', 'dog', 'bunny', 'pig']
print("Your list of animals are: {}, {}, {} and {}".format(*sample_list))
使用格式阅读此处的文档.
Mat*_*t P 10
这是一个有趣的问题!使用可变长度列表的.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'
| 归档时间: | 
 | 
| 查看次数: | 181542 次 | 
| 最近记录: |