Python 使用string.format的整数列表联接
如图所示,整数列表可以通过转换Python 使用string.format的整数列表联接,python,string,list,Python,String,List,如图所示,整数列表可以通过转换str然后将其合并来合并 顺便说一句,我想得到foobar 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 =
str
然后将其合并来合并
顺便说一句,我想得到foobar 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
)。我试过了
我认为它仍然没有吸引力是否有一种方法可以使用字符串连接整数列表。仅使用格式?
我可能没有理解您问题的要点,但您可以简单地扩展链接到的方法,如下所示:
>>> 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'
既然您喜欢吸引力,只想使用一行,并且只使用格式
,您可以这样做
'{} {} {}{}'.format('foo', 'bar', len(x), ' {}' * len(x)).format(*x)
# foo bar 10 0 1 2 3 4 5 6 7 8 9
您只需使用打印功能即可:
>>> 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
“不一致”“没有吸引力”。为什么?@LutzHorn不一致且不吸引人:我只想用一行字符串来解决问题。格式。你真的想存储该字符串,还是仅用于打印?仅用于打印谢谢!有没有像out='{}{}{}'.format('foo','bar',len(x),x)
这样简单的方法?@mskimm不幸的是,没有:(想不到,我不知道你可以链接format()调用:)
>>> 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