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开发者_如何学C\\.1\\.1
How can I achieve this? Why is it behaving this way?
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.
The string is exactly what it should be. The extra slashes are only in the display, not in the actual string.
\ 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.
精彩评论