Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用string.format的整数列表联接_Python_String_List - Fatal编程技术网

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