Python|用它的出现替换字符
有时,在使用Python时,我们可能会遇到需要用字符串中出现的字符的问题。这是一个特殊的问题,但可以在许多领域中应用。让我们讨论可以执行此任务的某些方式。
方法#1:使用循环
这是解决问题的粗鲁方法。在此,我们为字符串中的每个字符运行一个循环,并在每次增加计数器的同时执行替换。
# Python3 code to demonstrate working of
# Substitute character with its occurrence
# Using loop
# initializing string
test_str = "geeksforgeeks is best for geeks"
# printing original string
print("The original string is : " + test_str)
# initializing letter
test_let = 'g'
# Substitute character with its occurrence
# Using loop
res = ''
count = 1
for chr in test_str:
if chr == test_let:
res += str(count)
count += 1
else:
res += chr
# printing result
print("The string after performing substitution : " + str(res))
输出 :
The original string is : geeksforgeeks is best for geeks
The string after performing substitution : 1eeksfor2eeks is best for 3eeks
方法#2:使用 lambda + regex + next()
上述功能的组合可用于执行此任务。在此我们使用 lambda 执行迭代任务,正则表达式和 next() 用于执行计数迭代任务并找到目标字符。
# Python3 code to demonstrate working of
# Substitute character with its occurrence
# Using lambda + regex + next()
from itertools import count
import re
# initializing string
test_str = "geeksforgeeks is best for geeks"
# printing original string
print("The original string is : " + test_str)
# initializing letter
test_let = 'g'
# Substitute character with its occurrence
# Using lambda + regex + next()
cnt = count(1)
res = re.sub(r"g", lambda x: "{}".format(next(cnt)), test_str)
# printing result
print("The string after performing substitution : " + str(res))
输出 :
The original string is : geeksforgeeks is best for geeks
The string after performing substitution : 1eeksfor2eeks is best for 3eeks