theautistic9
theautistic9

Reputation: 69

How to delete string from a string in Python?

This can look like a simple question but not in my situation.

I have a list

list0 = ['amigohello','amigobye']

And i want to delete "amigo" from it. If I try:

for x in list0:
    print x.split("amigo")

It gives me next:

['', 'hello']
['', 'bye']

I tried:

for x in list0:
    x = str(x.split("amigo"))
    print x.split("[''")

Also:

for x in list0:
    print x.strip('amigo')

And it gives me:

hell
bye

The most strange is that in this output doesnt delete all 'o' if i change 'amigohello' to 'amigohoeollo'

And of course i tried with x.strip('amigo')[0]

What i just want to do is delete exactly on string everything that is "amigo", not a.m.i.g.o or ami.go., only if i found amigo without the [] problem or a solution to the [] problem. Thanks.

Upvotes: 1

Views: 33170

Answers (3)

theObserver
theObserver

Reputation: 127

list0 = [item.replace('amigo','') for item in list0]

Upvotes: 0

There's a replace method in which you can replace the undesired word for an empty string.

list0 = ['amigohello','amigobye']
for x in list0:
    print(x.replace("amigo", ""))  # hello, bye

Upvotes: 2

Moses Koledoye
Moses Koledoye

Reputation: 78564

You should use str.replace to replace exact appearances of the word amigo:

for x in list0:
    print x.replace("amigo", "")

'hello'
'bye'

Upvotes: 6

Related Questions