-1

I have a list of symbols that I want to replace by spaces in a string. Here is my code:

useless = ['.', ',', '!', '?', ':', '(', ')', '"', '[', ']']
message = 'Whatever. you; "want:)'

for sign in useless:
    while message.find(sign):
        message.replace(sign, ' ')

This results in an infinite loop that never stops. It's probably something easy but I'm on it for quite a long time now.. Any help would be great, thank you.

Ben
  • 1
  • 1
  • 2
    `message = message.replace(sign, ' ')` string.replace does not operate in place, but returns the modified string as strings are immutable in Python. – sberry Nov 04 '16 at 21:58

3 Answers3

5

message.replace() doesn't modify the string (in Python, strings are immutable, which means that you can't modify them in-place).

What you're looking for is:

message = message.replace(sign, ' ')

(Also see Francisco Couzo's answer for another bug.)

NPE
  • 486,780
  • 108
  • 951
  • 1,012
3

Besides having to reassign message to mesage.replace(sign, ' '), message.find(sign) returns -1 if it can't find the string, which is truthy.

Replace it with: sign in message.

Francisco
  • 10,918
  • 6
  • 34
  • 45
0

You could try a regular expression instead of a loop.

>>> import re 
>>> p = '[.,!?:";()\[\]]'
>>> message = 'Whatever. you; "want:)'
>>> re.sub(p, ' ', message)
'Whatever  you  want  '

As stated, replace returns a value, does not update in-place. Same with re.sub, as you can see.

For related reading, see Ways to strip punctuation from a string in Python

Community
  • 1
  • 1
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245