Python程序替换字符串中的每个第N个字符
给定一个字符串,任务是编写一个Python程序,用给定的值 K 替换字符串的每个第 N 个字符。
例子:
Input : test_str = “geeksforgeeks is best for all geeks”, K = ‘$’, N = 5
Output : geeks$orge$ks i$ bes$ for$all $eeks
Explanation : Every 5th character is converted to $.
Input : test_str = “geeksforgeeks is best for all geeks”, K = ‘*’, N = 5
Output : geeks*orge*ks i* bes* for*all *eeks
Explanation : Every 5th occurrence is converted to *.
方法 1:使用循环和 enumerate()
在这里,我们对每个字符执行一次迭代,并通过执行取模来检查它的第 N 个,即找到 N 的余数。如果第 N 个出现,则该字符被 K 替换。
例子
Python3
# initializing string
test_str = "geeksforgeeks is best for all geeks"
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = '$'
# initializing N
N = 5
res = ''
for idx, ele in enumerate(test_str):
# add K if idx is multiple of N
if idx % N == 0 and idx != 0:
res = res + K
else:
res = res + ele
# printing result
print("String after replacement : " + str(res))
Python3
# initializing string
test_str = "geeksforgeeks is best for all geeks"
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = '$'
# initializing N
N = 5
res = ''.join(ele if idx % N or idx == 0 else K for idx,
ele in enumerate(test_str))
# printing result
print("String after replacement : " + str(res))
输出:
The original string is : geeksforgeeks is best for all geeks
String after replacement : geeks$orge$ks i$ bes$ for$all $eeks
方法 2:使用生成器表达式、join() 和 enumerate()
在这种情况下,字符串的构造是使用 join() 进行的。 enumerate() 有助于获取所需的索引。生成器表达式提供了解决此问题的速记方法。
例子
蟒蛇3
# initializing string
test_str = "geeksforgeeks is best for all geeks"
# printing original string
print("The original string is : " + str(test_str))
# initializing K
K = '$'
# initializing N
N = 5
res = ''.join(ele if idx % N or idx == 0 else K for idx,
ele in enumerate(test_str))
# printing result
print("String after replacement : " + str(res))
输出:
The original string is : geeksforgeeks is best for all geeks
String after replacement : geeks$orge$ks i$ bes$ for$all $eeks