3

Is it possible to take a string, and convert all the characters into their Python escape sequences?

2 Answers 2

5

repr() escapes all the characters that need to be escaped

repr(string) 

There are other methods in the standard library for the likes of escaping URIs and so on

Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to escape all characters?
@Acorn, you could do something like this print "".join("\\x"+c.encode('hex') for c in "ABCDE")
3

Supports full escaping of both str and unicode (now produces the shortest escape sequence):

def escape(s): ch = (ord(c) for c in s) return ''.join(('\\x%02x' % c) if c <= 255 else ('\\u%04x' % c) for c in ch) for text in (u'\u2018\u2019hello there\u201c\u201d', 'hello there'): esc = escape(text) print esc # code below is to verify by round-tripping import ast assert text == ast.literal_eval('u"' + esc + '"') 

Output:

\u2018\u2019\x68\x65\x6c\x6c\x6f\x20\x74\x68\x65\x72\x65\u201c\u201d \x68\x65\x6c\x6c\x6f\x20\x74\x68\x65\x72\x65 

4 Comments

What about strings containing a mix of unicode characters and standard characters?
@Acorn the unicode \uABCD escape sequence will cover the full range of characters. Did you want the shortest possible escape sequence?
@Acorn I updated it to produce the shortest sequence it can, so chars whose ord(c) <= 255 will be encoded as \xAB form, even in unicode string.
@samplebias: Even better! (you forgot to change the output though)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.