0

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
  • 209,562
  • 33
  • 339
  • 356
  • 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
  • There isn't an "original form" to convert back to. The `\v` in the declaration of `myString` **does not** represent a backslash followed by a lowercase v; it represents a vertical tabulation character (which Python will represent back to you as `'\x0b'`). You cannot get the backslash and lowercase v back because *it was never there to begin with*. You can *replace* the vertical tabulation character, but you don't have a proper way in general to know whether you *should* (or *how*). Voting to close as a typo. – Karl Knechtel Aug 05 '22 at 03:35

2 Answers2

0

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,632
  • 9
  • 59
  • 117
-1
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,944
  • 2
  • 19
  • 43
  • 2
    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