use*_*541 2 python regex string replace
我有一个带有占位符的字符串,我想将索引附加到占位符上。
例如
'This @placeholder is @placeholder'
Run Code Online (Sandbox Code Playgroud)
应该成为
'This @param0 is @param1'
Run Code Online (Sandbox Code Playgroud)
假设我有一个包含 2 个值的参数列表(与 @placeholder 出现的次数匹配)。
一种可选的解决方案是。
result = ''
parts = my_text.split('@placeholder')
for i in range(0, len(params)):
result += '{}@param{}'.format(parts[i], i)
return result
Run Code Online (Sandbox Code Playgroud)
另一种选择是继续用当前索引替换占位符,但这意味着扫描字符串 len(params) 次。
for i in range(0, len(params)):
my_text = my_text.replace('@placeholder', '@param{}'.format(i), 1)
Run Code Online (Sandbox Code Playgroud)
在 python 中是否有更好的解决方案?
re.sub带有回调和计数器的简单解决方案怎么样?
>>> import itertools
>>> c = itertools.count()
>>> text = 'This @placeholder is @placeholder'
>>> re.sub(r'\b@placeholder\b', lambda x: f'@param{next(c)}', text)
'This @param0 is @param1'
Run Code Online (Sandbox Code Playgroud)