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

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)
Run Code Online (Sandbox Code Playgroud)

我想输出字符串是:

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'
Run Code Online (Sandbox Code Playgroud)

  • OP的问题不是方法而是参数的格式。`%` 运算符仅解包元组。 (2认同)
  • @SabreWolfy如果你在前面构造它,那么你可能会发现更容易命名你的占位符并使用dict来格式化结果字符串:`print u'%(blah)d BLAHS%(foo)d FOOS ...'%{'blah' :15,'foo':4}`. (2认同)
  • @SabreWolfy:在Python 2.7中,你可以省略字段编号:`s ='{} BLAH {} BLAH BLAH {} BLAH BLAH BLAH'` (2认同)
  • @kotchwane: * 函数是一个特殊的 python 关键字,它将作为列表的参数转换为争论列表:)。在我们的例子中,*x 将把 x 的 3 个成员传递给 format 方法。 (2认同)

inf*_*red 103

print s % tuple(x)
Run Code Online (Sandbox Code Playgroud)

代替

print s % (x)
Run Code Online (Sandbox Code Playgroud)

  • `print s%(x)`是OP写的,我只是引用他/她. (9认同)
  • `(x)`与`x`是一回事.将单个标记放在括号中对Python没有意义.你通常把括号放在`foo =(bar,)`中以便于阅读,但`foo = bar,`完全相同. (3认同)
  • 为清晰起见,我使用`(x)`表示法; 如果您以后添加其他变量,它还可以避免忘记括号. (2认同)

neo*_*bot 26

在此资源页面之后,如果x的长度不同,我们可以使用:

', '.join(['%.2f']*len(x))
Run Code Online (Sandbox Code Playgroud)

从列表中为每个元素创建占位符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]
Run Code Online (Sandbox Code Playgroud)


Jor*_*ley 17

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

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

但是,我仍然没有想出如何进行切片(在格式字符串内部'"{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))
Run Code Online (Sandbox Code Playgroud)

使用格式阅读此处的文档.

  • @kotchwane 星号将列表“扩展”为单独的有序参数。f(\*x) == f(x[0], x[1], ..., x[n])。同样,两个星号 (\*\*) 将字典扩展为关键字参数。 (4认同)

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'
Run Code Online (Sandbox Code Playgroud)


rya*_*lon 6

如果只是将任意值列表填充到字符串中,您可以执行以下操作,这与 @neobot 的答案相同,但更现代和简洁。

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

如果您连接在一起的已经是某种结构化数据,我认为最好做一些类似的事情:

>>> data = {"blah": 1, "foo": 2, "bar": 3}
>>> " ".join([f"{k} {v}" for k, v in data.items()])
'blah 1 foo 2 bar 3'
Run Code Online (Sandbox Code Playgroud)