NST
NST

Reputation: 11

How to replace multiple (non-unique) substrings in a string?

I have this string -

test_str = 'hello_2Testsmthhello_1smthhello_1'

and I have a list of strings -

list1 = ['hello_1', 'hello_2']

Now I want to replace hello_1 and hello_2 with a period(.). This is what I've tried -

for i in list1:
    h = test_str.replace(str(i), ".")
#print (h)

This gives me the string - .Testsmthhello_1smthhello_1

However, the expected output is - .Testsmth.smth.

Can anyone help me here?

Upvotes: 0

Views: 61

Answers (4)

Ash W
Ash W

Reputation: 30

You can simply change the h in the loop to test_str :)

for i in list1:
    test_str = test_str.replace(str(i), ".")

In your original loop, you did successfully replace the substrings with . in test_str but you didn't save this change. test_str stayed the same and h got a brand new value in each loop. As you can see by printing the values during the loop.

for i in list1:
    print(i)
    h = test_str.replace(str(i), ".")
    print(h)
    print(test_str)

Hopefully I explained this clearly.

Upvotes: 1

Sociopath
Sociopath

Reputation: 13426

You can use regex for it

import re

test_str = 'hello_2Testsmthhello_1smthhello_1'

pattern = r'hello_\d'

print(re.sub(pattern,'.', test_str))

Upvotes: 0

Gilseung Ahn
Gilseung Ahn

Reputation: 2624

It is because test_str is replaced only once. Do not use h for your intent.

for i in list1:
    test_str = test_str.replace(str(i), ".")

If you do not want to change test_str, then make a copy as follows.

import copy
h = copy.copy(test_str)

for i in list1:
    h = h.replace(str(i), ".")

Upvotes: 0

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9600

replace() returns a copy of the string with the replaced version so you need to assign it back to test_str:

test_str = 'hello_2Testsmthhello_1smthhello_1'
list1 = ['hello_1', 'hello_2']
for i in list1:
    test_str = test_str.replace(i, ".")
    
print(test_str) #.Testsmth.smth.

Upvotes: 0

Related Questions