Skip to content

How to unescape strings to undo the escaping that KGTK does #412

Answered by chalypso
szeke asked this question in Q&A
Discussion options

You must be logged in to vote

Here's a simple way to do this in Python properly handles escape sequences such as \t and \n and replaces everything else by the escaped character:

>>> kgtkval = r"abc\tfoo\n\'bar\|blah"
>>> kgtkval
"abc\\tfoo\\n\\'bar\\|blah"
>>> print(kgtkval)
abc\tfoo\n\'bar\|blah

# this does half the job, but doesn't replace \n or \t correctly:
>>> re.sub(r'\\([^nrt])', r'\1', kgtkval)
"abc\\tfoo\\n'bar|blah"
>>> print(_)
abc\tfoo\n'bar|blah

# here is one way to use Python eval to handle \n and \t:
>>> eval('"""%s"""' % re.sub(r'\\([^nrt])', r'\1', kgtkval))
"abc\tfoo\n'bar|blah"
>>> print(_)
abc	foo
'bar|blah

# here's a better way that doesn't use eval:
>>> bytes(re.sub(r'\\([^nrt])', r'\1', kgtkv…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by chalypso
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants