Suppose I have the following string in Python:
>>> example="""
... \nthird line
... [\t] <-tab in there
... [\n] <-\\n in there
... \v vtab
... 1\b2 should be only '2'
... this\rthat <- should be only 'that'
... """
If I print that, the various escaped characters (like \t for a tab) are interpolated into a human readable form:
>>> print example
third line
[ ] <-tab in there
[
] <-\n in there
vtab
2 should be only '2'
that <- should be only 'that'
What if I want to only produce a string with the various escape codes expanded or interpreted without printing it? Somthing like:
>>> exp_example = example.expandomethod()
(I have looked at the various string methods, decode, and format but none are working as in this example.)
Edit
OK — Thanks for the help for the thick scull on my part. I was convinced that these strings were being parsed, which they are, but it the display of them that was fooling me.
I worked this out in my own mind:
>>> cr='\012' # CR or \n in octal
>>> len(cr)
1
>>> '123'+cr
'123\n'
>>> '123\012' == '123\n'
True
As others have stated, when you type in your escaped string, or Python first interprets the string, the escape character
\and the character following are reduced to the single targeted character.However — if you are constructing a string that with to goal of producing unprintable characters from their escape sequence, str.decode([encoding[, errors]]) does what you want:
And this:
is a different result than this: