1

I have this interactive session:

>>> str = '192.168.1.1'
>>> str = str.replace('.','\.')
>>> str
'192\\.168\\.1\\.1'

I want the out put to be: 192\.168\.1\.1 instead of 192\\.168\\.1\\.1

How can I achieve this? Why is it behaving this way?

ehftwelve
  • 2,787
  • 2
  • 20
  • 25
  • Duplicate of http://stackoverflow.com/questions/2179493/adding-backslashes-without-escaping-python – cEz Jun 21 '11 at 21:39

3 Answers3

8

Use print str instead of str:

>> str = '192.168.1.1'
>>> str = str.replace('.','\.')
>>> str
'192\\.168\\.1\\.1'
>>> print str
192\.168\.1\.1

Your string is the one you expect it to be, but when you just dump the object, python is showing it to you in a form you could use to assign to another string - that means escaping the \ characters.

Carl Norum
  • 219,201
  • 40
  • 422
  • 469
3

The string is exactly what it should be. The extra slashes are only in the display, not in the actual string.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

\ is an escape character, so \ is required to add \ to the string by hiding its escape character nature.

If you use "print" before your string name, you'll see how it appears rather than what it actually contains.

carlbenson
  • 3,177
  • 5
  • 35
  • 54