Python – 替换字符串中的重复出现
有时,在使用Python字符串时,我们可能会遇到需要执行单词替换的问题。这是很常见的任务,并且已经讨论过很多次。但有时,要求是仅替换出现的重复项,即从第二次出现。这在许多领域都有应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用split() + enumerate()
+ 循环
上述功能的组合可用于执行此任务。在此,我们使用 split 分隔单词。在此,我们记住 set 中的第一次出现并检查该值是否在之前保存然后被替换是否已经发生。
# Python3 code to demonstrate working of
# Replace duplicate Occurrence in String
# Using split() + enumerate() + loop
# initializing string
test_str = 'Gfg is best . Gfg also has Classes now. \
Classes help understand better . '
# printing original string
print("The original string is : " + str(test_str))
# initializing replace mapping
repl_dict = {'Gfg' : 'It', 'Classes' : 'They' }
# Replace duplicate Occurrence in String
# Using split() + enumerate() + loop
test_list = test_str.split(' ')
res = set()
for idx, ele in enumerate(test_list):
if ele in repl_dict:
if ele in res:
test_list[idx] = repl_dict[ele]
else:
res.add(ele)
res = ' '.join(test_list)
# printing result
print("The string after replacing : " + str(res))
The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better .
The string after replacing : Gfg is best . It also has Classes now. They help understand better .
方法 #2:使用keys() + index()
+ 列表理解
这是可以执行此任务的另一种方式。在这种情况下,我们不需要记忆。这是解决此问题的一种线性方法。
# Python3 code to demonstrate working of
# Replace duplicate Occurrence in String
# Using keys() + index() + list comprehension
# initializing string
test_str = 'Gfg is best . Gfg also has Classes now. Classes help understand better . '
# printing original string
print("The original string is : " + str(test_str))
# initializing replace mapping
repl_dict = {'Gfg' : 'It', 'Classes' : 'They' }
# Replace duplicate Occurrence in String
# Using keys() + index() + list comprehension
test_list = test_str.split(' ')
res = ' '.join([repl_dict.get(val) if val in repl_dict.keys() and test_list.index(val) != idx
else val for idx, val in enumerate(test_list)])
# printing result
print("The string after replacing : " + str(res))
The original string is : Gfg is best . Gfg also has Classes now. Classes help understand better .
The string after replacing : Gfg is best . It also has Classes now. They help understand better .