Reputation: 23
I want to use make replacements on a text file which is
one two three pthree two ptwo one two ...(1000+ words)
such that output looks like 1 2 3 p3 2 p2 1 2 ....
My code looks like
dict = { 'zero':'0','one':'1','two':'2','three':'3','four':'4','five':'5','six':'6','seven':'7'}
x = 'one two three pthree two ptwo one two' #reading input from file
for k, v in dict.items():
x = x.replace(k, v)
I have tried these solutions str.replace and regex but both methods give me the same error which is
TypeError: replace() argument 2 must be str, not int
What does this error mean? And how should I resolve it? Thank You
Upvotes: 0
Views: 752
Reputation: 93
Running the code you have written in the question actually works. From the error I suspect that the dictionary you are actually working against is more like:
{ 'zero': 0, 'one': 1 } # etc
I.E the values are integers rather than strings. You can either correct whatever is creating the dictionary to ensure that the values have the right type, or you can cast to the correct type before calling replace
d = { 'zero': 0, 'one': 1, 'two': 2, 'three': 3 }
x = 'one two three pthree two ptwo one two' #reading input from file
for k, v in d.items():
x = x.replace(k, str(v))
Upvotes: 1