[英]python string substitute letter by its occurrence number
Suppose I have a string Hello, world
, and I'd like to replace all instances of o
by its occurrence number, ie get a sting: Hell1, w2rld
?假设我有一个字符串Hello, world
,我想用它的出现次数替换o
的所有实例,即得到一个刺痛: Hell1, w2rld
?
I have found how to reference a numbered group, \\g<1>
, but it does require a group number.我找到了如何引用编号组\\g<1>
,但它确实需要一个组号。
Is there are way to do what I want in python?有没有办法在python中做我想做的事?
Update: Sorry for not mentioning that I was indeed looking for a regexp solution, not just a string.更新:很抱歉没有提到我确实在寻找正则表达式解决方案,而不仅仅是字符串。 I have marked the solution I liked the best, but thank for all contributions, they were cool!我已经标记了我最喜欢的解决方案,但感谢所有贡献,他们很酷!
For a regular expression solution :对于正则表达式解决方案:
import re
class Replacer:
def __init__(self):
self.counter = 0
def __call__(self, mo):
self.counter += 1
return str(self.counter)
s = 'Hello, World!'
print(re.sub('o', Replacer(), s))
Split the string on the letter "o" and reassemble it by adding the index of the part in front of each part (except the first one):拆分字母“o”上的字符串并通过在每个部分(第一个除外)前面添加部分的索引来重新组合它:
string = "Hello World"
result = "".join(f"{i or ''}"+part for i,part in enumerate(string.split("o")))
output:输出:
print(result)
# Hell1 W2rld
Using itertools.count
使用itertools.count
Ex:前任:
import re
from itertools import count
c = count(1)
s = "Hello, world"
print(re.sub(r"o", lambda x: "{}".format(next(c)), s))
#or
print(re.sub(r"o", lambda x: f"{next(c)}", s))
# --> Hell1, w2rld
You don't need regex for that, a simple loop will suffice:您不需要正则表达式,一个简单的循环就足够了:
sample = "Hello, world"
pattern = 'o'
output = ''
count = 1
for char in sample:
if char == pattern:
output += str(count)
count += 1
else:
output += char
print(output)
>>> Hell1, w2rld
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.