Python Forum

Full Version: converting backslash codes
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i know python has such a thing but cannot remember the terms or names for this.  my guesses are not helping my search.

foo('\\'+'n'+'\\'+'t') -> '\n\t'

e.g having the backslash codes (any of them, not just these 2), convert them to the actual vales.  this is conversion done to string literals somewhere in the python interpreter.  but i have seen this before, so i know exists as a simple function call, but my searches are all failing. repr() does the reverse.
I'm not quite sure I understand what you want.

Does this hit on it?
>>> chr(10)
'\n'
>>> ord('\n')
10
Edit:
I think these links hit on your question actually:  
How do I un-escape a backslash-escaped string in python?
how do I .decode('string-escape') in Python3?
i was hoping it was usable in python 2.  i guess i will have to get this old code cleaned up and use it..

You mean marking the string as 'raw' by putting "r" in front of it?
>>> x = '\\n'
>>> y = r'\n'
>>> x == y
True
warning: very old thread

(Oct-18-2016, 03:08 PM)nilamo Wrote: [ -> ]You mean marking the string as 'raw' by putting "r" in front of it?
>>> x = '\\n'
>>> y = r'\n'
>>> x == y
True

no.

i mean converting the kinds of backslash codes you might see expressed in source code, from being in actual strings to the binary result.

if i have code that reads input into a string and i type in a backslash and an 'r' i will have 2 characters, a backslash and an 'r'. source code to get exactly the same thing would be '\r'. but source code is merely explaining this; not how it is actually gotten. wherever those 2 characters come from, i want to apply the same effect as you see in source code:
    foo = '\r'
in the above case the variable named foo will end up with just 1 character. what i want (and have coded) is a function to do that.

my struggle has been explaining what i am doing. the "raw" concept is not what i am doing, although a reference to it might explain it to you. i'm thinking of it as an encoding.

perhaps this code would explain better what i have and what i want that can do the conversion
   abc = chr(92)
   xyz = chr(114)
   woot = convert(abc+xyz)
   print(ord(woot))
this would print out 13. what i want is that convert() function in a form that supports all such control codes.