繁体   English   中英

字符串格式

[英]String formatting

我有一个列表过滤器= ['a','b','c']。 我需要从列表“ item -a item -b item -c”中构造以下字符串。 哪种方法最有效? 通常,列表过滤器包含100到200个项目,每个项目的长度为100-150。这是否会导致溢出? 以及支持的最大字符串长度是多少?

一种更清洁的方法:

filter = ['a', 'b', 'c']
" ".join(["item -%s" % val for val in filter])

例如,这在大型数组上工作良好。 filter = ['a'*1000] * 1000

您可以使用join (我相信join在Python 3.0中是相同的):

>>> l = ['a','b','c']
>>> print ' item -'.join([''] + l)
>>> ' item -a item -b item -c'

>>> print ' item -'.join([''] + l).lstrip(' ') # eat the leading space
>>> 'item -a item -b item -c'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM