LaVOZs

The World’s Largest Online Community for Developers

'; How do I remove a list of substrings from a given string in Python? - LavOzs.Com

So I have this string, and I'm iterating over a list of substrings to remove. In Ruby, where strings are mutable, I would just be able to keep changing the original string in place. But I'm running into issues figuring this out due to strings being immutable in Python.

If this is my string, and I'm trying to remove substrings in the following list (times):

string = "Play soccer tomorrow from 2pm to 3pm @homies"
times = ['tomorrow', 'from 2pm to 3pm']

How do I get this string as the desired return?

removed_times = "Play soccer @homies"

Edit: different from suggested questions b/c of multiple substrings

You could just use str.replace() to replace the substrings with "". This also means that the final result would need to be split and joined by " " to only have one whitespace between the words after replacing. You can use str.split() and str.join() for this.

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

Note: Strings are immutable in python, so you cannot simply modify it in-place withstring.replace(time, ""). You need to reassign the string with string = string.replace(time, "").

You could split the string on the substrings, and then join it back together:

string = "Play soccer tomorrow from 2pm to 3pm @homies"
times = ['tomorrow', 'from 2pm to 3pm']
for t in times:
    string = ''.join(string.split(t))

Note that this returns the string 'Play soccer @homies' as spaces aren't caught and removed in your times.

string = "Play soccer tomorrow from 2pm to 3pm @homies"
times = ['tomorrow', 'from 2pm to 3pm']
removed_times = string
for x in times:
    removed_times = removed_times.replace(' ' + x + ' ', ' ')
print(removed_times)
#Play soccer @homies
Related
Calling an external command from Python
Finding the index of an item given a list containing it in Python
How to check if a string contains a substring in Bash
How do I read / convert an InputStream into a String in Java?
How do I get a substring of a string in Python?
How to replace all occurrences of a string?
How to remove items from a list while iterating?
How to check whether a string contains a substring in JavaScript?
Does Python have a string 'contains' substring method?
How do I check if a string contains a specific word?