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?
4 Answers 4
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.
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.
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), ".")
You can use regex
for it
import re
test_str = 'hello_2Testsmthhello_1smthhello_1'
pattern = r'hello_\d'
print(re.sub(pattern,'.', test_str))
h = test_str.replace(str(i), ".")
, do you expect this to change the value oftest_str
? Why or why not? If it doesn't change, then can you explain how you expect the loop to work?h = test_str.replace(str(i), ".")
, soh
ends up with the result of doing the first replacement, andtest_str
is the same as before. Right? So, what do you think will happen the second time through the loop, given thattest_str
didn't change? Again: try to think about your code first, and step through the logic of it.