我的主要要求是将模板添加到字符串列表,并将其作为单个字符串连接。
def give_str(input_list, template, delimiter="()", joiner=""):
#Some operation happens here
return output_string
Input: give_str(["first", "second", "third"], ["count", "rank"], delimiter="()", joiner=",")
Output: "count(rank(first)),count(rank(second)),count(rank(third))"
现在,我正在做这样的事情:
def give_str(input_list, template, delimiter="()", joiner=","):
output_string = ""
template_string = delimiter[0].join(template) + delimiter[0]
item_close = delimiter[-1] * len(template)
output_string = joiner.join(template_string+item+item_close for item in input_list if item)
return output_string
我对多个字符串添加不满意,即使这很简单明了。是否有可以简化此过程的内置库(只有内置库,因为我无法安装任何第三方软件包)?在意义上简化
暗示的另一件事是,分隔符是单个字符还是双字符。可能的分隔符:“,”,“ |”,“()”,“ []”,...
注意:如果您投反对票,请发表评论,说明为什么您认为这没有用。我和将来可能会问这个问题的人可能会从您的观点中学到一两个东西。
较干净的方法是使用string.template
>>> from string import Template
>>> def give_str(input_list, template, delimiter="()", joiner=""):
s = Template("$temp$left$inner$right")
data = []
for elem in input_list:
for t in reversed(template):
elem = s.substitute(
temp=t,
left = delimiter[0],
right = delimiter[-1],
inner = elem)
data.append(elem)
return joiner.join(data)
>>> give_str(["first", "second", "third"], ["count", "rank"], delimiter="()", joiner=",")
'count(rank(first)),count(rank(second)),count(rank(third))'
>>> give_str(["first", "second", "third"], ["count", "rank"], delimiter="|", joiner=",")
'count|rank|first||,count|rank|second||,count|rank|third||'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句