Reputation: 21007
My question is simple. Lets assume you have string in python like this Foo '" \ Bar
.
What is the correct way to convert it to valid python expression like 'Foo \'" \\ Bar'
(so you just simply can copy&paste it to python interpreter and it'll work)?
I thought of '"{}"'.format(some replace magic)
, but there's gotta be better solution.
Upvotes: 2
Views: 107
Reputation: 1125398
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('\'"'))
'\'"'
Upvotes: 3
Reputation: 388463
That’s exactly what repr
is meant to do:
>>> x = '''Foo '" \ Bar'''
>>> repr(x)
'\'Foo \\\'" \\\\ Bar\''
>>> print(repr(x))
'Foo \'" \\ Bar'
Upvotes: 1