简体   繁体   English

用到目前为止已出现的次数替换每次出现的字符串

[英]Replace every occurrence of a string with the number of times it has occurred so far

I have a string with placeholders and I want to attach an index to wach of the placeholders. 我有一个带占位符的字符串,我想在每个占位符上附加一个索引。

eg 例如

'This @placeholder is @placeholder'

Should become 应该成为

'This @param0 is @param1'

Assuming I have a list of params with 2 values(matches the number of time @placeholder occurs) . 假设我有一个带有2个值的参数列表(匹配@placeholder出现的时间)。

One optional solution would be. 一种可选的解决方案是。

result = ''
parts = my_text.split('@placeholder')
for i in range(0, len(params)):
  result += '{}@param{}'.format(parts[i], i)
return result

Another option is to keep replacing the placeholder with the current index, but this means scanning the string len(params) times. 另一个选择是继续用当前索引替换占位符,但这意味着扫描字符串len(params)次。

for i in range(0, len(params)):
  my_text = my_text.replace('@placeholder', '@param{}'.format(i), 1)

is there a better solution for doing this in python? 在python中有更好的解决方案吗?

How about a simple re.sub solution with a callback and counter? 一个带有回调和计数器的简单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'

Using the answer by @Ajax1234 I can just replace the place holder with {} and use formatting with an array. 使用@ Ajax1234的答案,我可以将占位符替换为{},并使用数组格式化。

my_text = 'This param{} is param{}'
print(my_text.format(i for i in range(len(params))]))

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

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