Reputation: 1219
I want to use string.replace using for loop. This is my code:
new = ['p','q','r']
my_str = 'there are two much person a, person b, person c.'
old = ['a','b','c']
for i in range(0,len(old)):
my_str = string.replace(my_str,old[i],new[i])
print(my_str)
But it is giving me error:
TypeError: 'str' object cannot be interpreted as an integer
Desired output:
there are two much person p, person q, person r.
This is just an example, I want to run a for loop for 10,000 length list.
Upvotes: 1
Views: 27472
Reputation: 2656
Try
new = ['p','q','r']
my_str = 'there are two much person a, person b, person c.'
old = ['a','b','c']
for i in range(len(old)):
my_str = my_str.replace(old[i],new[i])
print(my_str)
but that is propably not very fast
If entries in old are all letters-only you can do
import re
new = ['p','q','r']
my_str = 'there are two much person a, person b, person c.'
old = ['a','b','c']
word=re.compile(r"\w*") # word characters
old_new=dict(zip(old,new))
ong=old_new.get
my_str=word.sub((lambda s:ong(s,s)),my_str)
print(my_str)
this also avoids the double replacement problem if an entry is in both old and new (not avoided in the shorter solution)
Upvotes: 3
Reputation: 82889
Actually, I can not reproduce your problem; your code runs fine on Python 2.7. However, there are better ways to do it. First, instead of using a range
, you could zip
the old
and new
lists:
for i in range(0,len(old)):
my_str = string.replace(my_str,old[i],new[i])
However, this will still replace the a
in are
and the c
in much
, and it might also replace characters that were introduced in an earlier replacement, which is probably not what you want. Instead, you could use the re
module, joining the strings to be replaced with |
to a regex and delimiting it with \b
word boundary characters, e.g. \b(a|b|c)\b
in your case, and use a dictionary to look up the proper replacements.
d = dict(zip(old, new))
p = r'\b(' + '|'.join(old) + r')\b'
my_str = re.sub(p, lambda m: d.get(m.group()), my_str)
Result: there are two much person p, person q, person r.
Upvotes: 2
Reputation: 31885
string.replace()
is available on Python 2.x but deprecated in python 3.x.
Below is how you can use it in Python 3.x
str.replace(old, new[, count]) Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.
In your case, it is my_str.replace(old[index], new[index])
Upvotes: 1