使用string.format连接整数列表
在这个关于用Python连接整数列表的讨论中,我们可以通过先把整数转换成字符串,然后再把它们连接起来。
顺便说一下,我想得到的结果是 foo bar 10 0 1 2 3 4 5 6 7 8 9
,其中前面是几个数据(foo
和 bar
),接着是列表的大小 10
,然后是列表中的元素。
我使用了 string.format
,代码如下:
x = range(10)
out = '{} {} {} {}'.format('foo', 'bar', len(x), x)
这样 out
的结果会是 foo bar 10 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
为了处理这个问题,我可以把代码改成:
out = '{} {} {} '.format('foo', 'bar', len(x)) + ' '.join([str(i) for i in x])
但是这样看起来不太一致(混用了 string.format
和 join
)。我尝试了:
slot = ' {}' * len(x)
out = ('{} {} {}' + slot).format('foo', 'bar', len(x), *x)
我觉得这样还是不太好看。有没有办法只用 string.format
来连接整数列表呢?
3 个回答
3
你可以直接使用打印函数来做到这一点:
>>> from __future__ import print_function #Required for Python 2
>>> print('foo', 'bar', len(x), *x)
foo bar 10 0 1 2 3 4 5 6 7 8 9
5
我可能没有完全理解你的问题,但你可以简单地按照你提供的链接的方法进行扩展,像这样:
>>> x = range(10)
>>> out = " ".join(map(str, ["foo", "bar", len(x)] + x))
>>> out
'foo bar 10 0 1 2 3 4 5 6 7 8 9'
5
因为你喜欢简洁美观,想用一行代码,并且只用format
这个方法,你可以这样做:
'{} {} {}{}'.format('foo', 'bar', len(x), ' {}' * len(x)).format(*x)
# foo bar 10 0 1 2 3 4 5 6 7 8 9