2

I need to check a string for some symbols and replace them with a whitespace. My code:

string = 'so\bad'

symbols = ['•', '!', '"', '#', '$', '%', '&', '\'', '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '>', '=', '?', '@', '[', ']', '\\', '^', '_', '`', '{', '}', '~', '|', '"', '⌐', '¬', '«', '»', '£', '$', '°', '§', '–', '—']

for symbol in symbols:
    string = string.replace(symbol, ' ')

print string
>> sad

Why does it replace a\b with nothing?

mattsap
  • 3,790
  • 1
  • 15
  • 36
Hyperion
  • 2,515
  • 11
  • 37
  • 59

4 Answers4

3

This is because \b is ASCII backspace character:

>>> string = 'so\bad'
>>> print string
sad

You can find it and all the other escape characters from Python Reference Manual.

In order to get the behavior you expect escape the backslash character or use raw strings:

# Both result to 'so bad'
string = 'so\\bad'
string = r'so\bad'
Community
  • 1
  • 1
niemmi
  • 17,113
  • 7
  • 35
  • 42
1

The issue you are facing is the use of \ as a escape character.
\b is a special character (backspace)

Use a String literal with prefix r. With the r, backslashes \ are treated as literal

string = r'so\bad'
Copy and Paste
  • 496
  • 6
  • 16
0

You are not replacing anything "\b" is backspace, moving your cursor to the left one step.

tfv
  • 6,016
  • 4
  • 36
  • 67
0

Note that even if you omit the symbols list and your for symbol in symbols: code, you will always get the result "sad" when you print string. This is because \b means something as an ascii character, and is being interpreted together.

Check out this stackoverflow answer for a solution on how to work around this issue: How can I print out the string "\b" in Python

Community
  • 1
  • 1
Projski
  • 181
  • 8