繁体   English   中英

使用列表替换字符串中的子字符串

[英]Replace substring in a string using a list

我正在寻找一种更 Pythonic 的方法来用列表中找到的值替换字符串中已知长度的占位符。 它们应该按顺序更换,并且只能使用一次。 例如使用值:

replaceVals = ['foo', 'bar']

origStr = 'I went to the ? to get ?'

我希望得到:

newStr = 'I went to the foo to get bar'

我能够通过以下循环获得所需的结果,但我觉得应该有比使用这样的循环更好的方法来解决这个问题。

for i in range(len(replaceVals)):
   origStr = origStr.replace('?', replaceVals[i], 1)

:这是一个使用的想法:

replaceVals = iter(['foo', 'bar'])
origStr = 'I went to the ? to get ?'

(' ').join(next(replaceVals) if i == '?' else i for i in origStr.split())

输出:

'I went to the foo to get bar'

做这种方式的好处是,在项目的金额replaceVals不必匹配要替换的项目数量origStr

replaceVals = iter(['foo', 'bar', 'other'])
origStr = 'I went to the ? to get ?'

(' ').join(next(replaceVals) if i == '?' else i for i in origStr.split())
#'I went to the foo to get bar'

但是,在这些情况下使用字符串格式会导致错误。

您可以使用字符串的replaceformat方法,如下所示:

origStr.replace('?','{}').format(*replaceVals)

Out[334]: 'I went to the foo to get bar'

@roganjosh 在评论中的回答可能是最好的,尽管 OP 足够抽象,不清楚他的真实情况是什么。 我很好奇是否可以使用出现在 Python3 中的 f-strings 来做到这一点。 使 f-string 不如 @roganjosh 有吸引力的原因是,通过.format()调用解压缩替换序列非常容易。 也就是说,如果你想尝试一个 f 字符串,这样的事情会起作用:

replaceVals = ['foo', 'bar'] 
stream = iter(replaceVals)
f'I went to the {stream.next()} to get {stream.next()}'

字符串

r=["foo","bar"]
origStr = f'I went to the {r[0]} to get {r[1]}'

origStr
Out[21]: 'I went to the foo to get bar'

您可以使用'?'拆分字符串 ,然后使用itertools.zip_longest将结果列表中的子字符串与replaceVals替换字符串replaceVals并以空字符串作为填充值,并在使用生成器表达式展平后连接字符串对:

from itertools import zip_longest
''.join(i for p in zip_longest(origStr.split('?'), replaceVals, fillvalue='') for i in p)

暂无
暂无

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

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