Python|从字符串中删除子字符串列表
有时,在使用Python字符串时,我们可能会遇到需要从字符串中删除子字符串的问题。这很容易,而且以前解决过很多次。但有时,我们会处理需要删除的字符串列表并相应地调整字符串。让我们讨论实现此任务的某些方法。
方法#1:使用循环+ replace()
上述功能的组合可以用来解决这个问题。在此,我们使用 replace() 执行多个字符串的替换。
# Python3 code to demonstrate working of
# Remove substring list from String
# Using loop + replace()
# initializing string
test_str = "gfg is best for all geeks"
# printing original string
print("The original string is : " + test_str)
# initializing sub list
sub_list = ["best", "all"]
# Remove substring list from String
# Using loop + replace()
for sub in sub_list:
test_str = test_str.replace(' ' + sub + ' ', ' ')
# printing result
print("The string after substring removal : " + test_str)
输出 :
The original string is : gfg is best for all geeks
The string after substring removal : gfg is for geeks
方法 #2:使用replace() + join() + split()
上述功能的组合可以用来解决这个问题。在此,我们使用 join() + split() 执行处理单个空间的任务。
# Python3 code to demonstrate working of
# Remove substring list from String
# Using replace() + join() + split()
# initializing string
test_str = "gfg is best for all geeks"
# printing original string
print("The original string is : " + test_str)
# initializing sub list
sub_list = ["best", "all"]
# Remove substring list from String
# Using replace() + join() + split()
for sub in sub_list:
test_str = test_str.replace(sub, ' ')
res = " ".join(test_str.split())
# printing result
print("The string after substring removal : " + res)
输出 :
The original string is : gfg is best for all geeks
The string after substring removal : gfg is for geeks