You can use the unicode_escape
codec; this produces a bytes
instance:
>>> example = 'Foo \'" \\ Bar'
>>> print(example)
Foo '" \ Bar
>>> print(example.encode('unicode_escape'))
b'Foo \'" \\\\ Bar'
>>> example.encode('unicode_escape')
b'Foo \'" \\\\ Bar'
unicode_escape
expliticly produces valid python string literals:
Produce a string that is suitable as Unicode literal in Python source code
To go back to Unicode, simply decode from ASCII:
>>> print(example.encode('unicode_escape').decode('ascii'))
Foo '" \\ Bar
>>> example.encode('unicode_escape').decode('ascii')
'Foo \'" \\\\ Bar'
Alternatively, use repr()
:
>>> repr(example)
'\'Foo \\\'" \\\\ Bar\''
>>> print(repr(example))
'Foo \'" \\ Bar'
Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to
eval()
, otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object.
The output of repr()
of a string can be pasted straight back into a Python interpreter without additional formatting.
Note that repr()
and unicode_escape
only escape quotes when absolutely necessary. Only when both styles of quoting, single and double, are present does one of these get escaped:
>>> print(repr('\''))
"'"
>>> print(repr('\"'))
'"'
>>> print(repr('\'"'))
'\'"'