1

I want to convert the escaped characters back to the original form:

>>> myString="\\10.10.10.10\view\a"
>>> myString
'\\10.10.10.10\x0biew\x07'
>>>desiredString=fun(myString)
>>>print desiredString
'\\10.10.10.10\view\a'

I researched quite a lot and could not find a solution I am using Python2.6.

Psidom
  • 195,464
  • 25
  • 298
  • 322
  • Possible duplicate of [How do I un-escape a backslash-escaped string in python?](http://stackoverflow.com/questions/1885181/how-do-i-un-escape-a-backslash-escaped-string-in-python) – Wiktor Stribiżew Aug 11 '16 at 13:10

3 Answers3

1

Ideally you should use the python builtin string functions or parsing properly your input data so you'd avoid these post-transformations. In fact, these custom solutions are not encouraged at all, but here you go:

def fun(input_str):
    cache = {
        '\'':"\\'",
        '\"':'\\"',
        '\a':'\\a',
        '\b':'\\b',
        '\f':'\\f',
        '\n':'\\n',
        '\r':'\\r',
        '\t':'\\t',
        '\v':'\\v'
    }

    return "".join([cache.get(m,m) for m in list(input_str)])

tests = [
    "\\10.10.10.10\view\a",
    "\'",
    '\"',
    '\a',
    '\b',
    '\f',
    '\n',
    '\r',
    '\t',
    '\v'
]

for t in tests:
    print repr(t)," => ",fun(t)
BPL
  • 9,532
  • 7
  • 47
  • 105
0
myString=r"\\10.10.10.10\view\a" 
myString
'\\\\10.10.10.10\\view\\a'
print myString
\\10.10.10.10\view\a

r'...' is byte strings

galaxyan
  • 5,527
  • 2
  • 18
  • 41
  • 1
    Not quite. `r'...'` is a raw string literal. In Python 2 all non-Unicode strings are byte strings. – PM 2Ring Aug 11 '16 at 13:16
0

The \v and \a are interpreted as specials characters while printing. Don't worry, just add another backslash to avoid this.

>>> myString="\\10.10.10.10\\view\\a"
>>> print(myString)
\10.10.10.10\view\a

Edit: Or use repr:

>>> myString=r"\\10.10.10.10\view\a"
>>> print myString
\\10.10.10.10\view\a
Kruupös
  • 4,484
  • 3
  • 24
  • 39