0

I want to replace $ to \$ in python3, how could I do that?

>>> import re
>>> s = 'Google Buys Fitbit for $2.1B'
>>> body.replace('$', "\$")
'Google Buys Fitbit for \\$2.1B'
>>> re.compile(r'\$').sub('\\$', body)
>>> 'Google Buys Fitbit for \\$2.1B'
Stephen Rauch
  • 44,696
  • 30
  • 102
  • 125

1 Answers1

0

\ is a special symbol. If you want to have this symbol in you string, you have to repeat it twice, like this: '\\' -- and remember this is not 2 (two), but actually ONE '\', it's just the rules about this particular symbol.

lenik
  • 22,629
  • 4
  • 31
  • 41