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
  • 47,830
  • 31
  • 106
  • 135

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
  • 23,228
  • 4
  • 34
  • 43