I need a way for my function to take in a string at runtime and remove the backslashes while KEEPING the character it is prepended to. So for \a I must get a. This must also work for nonescaped characters like \e -> e.
I've scoured the internet looking for a general solution to this problem, but there does not appear to be one. The best solution I have found uses a dictionary to build the string from scratch like: How to prevent automatic escaping of special characters in Python
escape_dict={'\a':r'\a',
'\b':r'\b',
'\c':r'\c',
'\f':r'\f',
'\n':r'\n',
'\r':r'\r',
'\t':r'\t',
'\v':r'\v',
'\'':r'\'',
'\"':r'\"',
'\0':r'\0',
'\1':r'\1',
'\2':r'\2',
'\3':r'\3',
'\4':r'\4',
'\5':r'\5',
'\6':r'\6',
'\7':r'\7',
'\8':r'\8',
'\9':r'\9'}
def raw(text):
"""Returns a raw string representation of the string"""
new_string=''
for char in text:
try:
new_string += escape_dict[char]
except KeyError:
new_string += char
return new_string
However this fails in general because of conflicts between the escaped numbers and escaped letters. Using the 3 digit numbers like \001 instead of \1 also fails because the output will have additional numbers in it which defeats the purpose. I should simply remove the backslash. Other proposed solutions based on encodings like the one found here Process escape sequences in a string in Python
also does not work because this converts just converts the escape characters into the hex code. \a gets converted to \x07. Even if were to somehow remove this the character a is still lost.