Domanda

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.

È stato utile?

Soluzione

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('\'"'))
'\'"'

Altri suggerimenti

That’s exactly what repr is meant to do:

>>> x = '''Foo '" \ Bar'''
>>> repr(x)
'\'Foo \\\'" \\\\ Bar\''
>>> print(repr(x))
'Foo \'" \\ Bar'
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top