如何从 Python 中的给定字符串中删除子字符串列表?

Hoj*_*Kim 1 python string substring python-3.x

所以我有这个字符串,并且我正在迭代要删除的子字符串列表。在 Ruby 中,字符串是可变的,我只能不断地更改原始字符串。但由于 Python 中的字符串是不可变的,我在解决这个问题时遇到了问题。

如果这是我的字符串,并且我尝试删除以下列表中的子字符串(次):

string = "Play soccer tomorrow from 2pm to 3pm @homies"
times = ['tomorrow', 'from 2pm to 3pm']
Run Code Online (Sandbox Code Playgroud)

如何获得该字符串作为所需的返回值?

removed_times = "Play soccer @homies"

编辑:与多个子字符串的建议问题 b/c 不同

Roa*_*ner 5

您只需使用str.replace()来替换子字符串""。这也意味着最终结果需要进行拆分和连接," "以便替换后单词之间只有一个空格。为此,您可以使用str.split()and 。str.join()

string = "Play soccer tomorrow from 2pm to 3pm @homies"

times = ["tomorrow", "from 2pm to 3pm"]

for time in times:
    string = string.replace(time, "")

print(" ".join(string.split()))
# Play soccer @homies
Run Code Online (Sandbox Code Playgroud)

注意:字符串在 python 中是不可变的,因此您不能简单地使用就地string.replace(time, "")修改它。您需要使用 重新分配字符串string = string.replace(time, "")