print string as raw string

Scott David Daniels Scott.Daniels at Acm.Org
Tue Feb 17 20:01:00 CET 2009

Steven D'Aprano wrote:
> Diez B. Roggisch wrote:
>> Mirko Dziadzka schrieb:
>>> I'm trying to find a way to output strings in the raw-string format, e.g.
>>> print_as_raw_string(r"\.") should output r"\." instead of "\\."  ...
> In any case, this is just a variation of what repr() does.
>>>> repr(r'\.')
> "'\\\\.'"
> What the OP seems to want is something like:...  a barely tested version:
> def raw_repr(s):
>     """Return the repr of string s as a raw-string."""
>     r = repr(s)
>     if '\\\\' in r:
>         r = "r" + r.replace('\\\\', '\\')
>     assert not r.endswith('\\')
>     return r
The big issue I see is that lots of values cannot be represented
as raw strings.  Your code checks for a final '\', but many "control"
characters and the quote marks are also at issue.

raw_repr('["\']a\x13\xfebc\\de') should contain several nasty cases.

--Scott David Daniels
Scott.Daniels at Acm.Org

More information about the Python-list mailing list