Python|在出现 K 次后替换字符
有时,在使用Python字符串时,我们可能会遇到需要在某些字符重复后执行字符替换的问题。这可以应用于许多领域,包括日间和竞争性编程。
方法#1:使用循环+字符串切片
这是可以解决此问题的蛮力方式。在此,我们在字符串上运行一个循环并跟踪出现次数并在超过 K 次出现时执行替换。
# Python3 code to demonstrate working of
# Replace characters after K occurrences
# Using loop + string slices
# initializing string
test_str = "geeksforgeeks is best for geeks"
# printing original string
print("The original string is : " + test_str)
# initializing K
K = 2
# initializing Repl char
repl_char = "*"
# Replace characters after K occurrences
# Using loop + string slices
for sub in set(test_str):
for idx in [idx for idx in range(len(test_str)) if test_str[idx] == sub][K:]:
test_str = test_str[:idx] + repl_char + test_str[idx + 1:]
# printing result
print("The string after performing replace : " + test_str)
输出 :
The original string is : geeksforgeeks is best for geeks
The string after performing replace : geeksforg**ks i* b**t*for******
方法 #2:使用join() + count() + enumerate()
这是可以执行此任务的简写。在此,我们使用 count() 来检查字符串的计数,而 join() 和 enumerate() 可用于执行新字符串构造的任务。
# Python3 code to demonstrate working of
# Replace characters after K occurrences
# Using join() + count() + enumerate()
# initializing string
test_str = "geeksforgeeks is best for geeks"
# printing original string
print("The original string is : " + test_str)
# initializing K
K = 2
# initializing Repl char
repl_char = "*"
# Replace characters after K occurrences
# Using join() + count() + enumerate()
res = "".join(chr if test_str.count(chr, 0, idx) < K
else repl_char for idx, chr in enumerate(test_str))
# printing result
print("The string after performing replace : " + res)
输出 :
The original string is : geeksforgeeks is best for geeks
The string after performing replace : geeksforg**ks i* b**t*for******