Hojung Kim
Hojung Kim

Reputation: 153

How do I remove a list of substrings from a given string in Python?

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

Upvotes: 1

Views: 2973

Answers (3)

RoadRunner
RoadRunner

Reputation: 26335

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 with string.replace(time, ""). You need to reassign the string with string = string.replace(time, "").

Upvotes: 5

Kiran Indukuri
Kiran Indukuri

Reputation: 412

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

Upvotes: 0

Oliver.R
Oliver.R

Reputation: 1368

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.

Upvotes: 2

Related Questions