0

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

4
  • 4
    The code you posted works without any errors though. Commented Oct 9, 2020 at 8:51
  • Yep, seems to be working, see repl.it/@ChristianBauman/WoozyAggressiveUnix Commented Oct 9, 2020 at 8:54
  • TypeError: replace() argument 2 must be str, not int Well this error just tells you that you need to put in a str type but you are giving it int. Try first converting it to str using str() function. Probably you're not just providing much details on your question. Commented Oct 9, 2020 at 8:56
  • 2
    Also, it replaces every occurance. For ex: 'phone' will be 'ph1', which you might not be anticipating. Commented Oct 9, 2020 at 8:57

1 Answer 1

1

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.