print string as raw string

Steven D'Aprano steve at pearwood.info
Tue Feb 17 07:21:16 EST 2009


Diez B. Roggisch wrote:

> Mirko Dziadzka schrieb:
>> Hi all
>> 
>> 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 "\\."
>> 
>> Is there a better way than writing your own print function? Some magic
>> encoding?
> 
> There is no need to do this. 

How do you know? Perhaps the OP is writing a test suite where he needs to
confirm that tens of thousands of raw strings are converted correctly, and
he'd rather write a Python script to generate those raw strings than to
type them up by hand. In this case though, the OP would be better off
generating the raw strings systematically, rather than trying to go
backwards.

In any case, this is just a variation of what repr() does.

>>> repr(r'\.')
"'\\\\.'"

What the OP seems to want is something like:

>>> raw_repr('\\\\.')  # or r'\.' or '\x5c.' etc.
"r'\.'"


I don't think that's necessarily a silly function to have, although what it
is useful for (apart from my contrived example above), I don't know.

Here is 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


>>> raw_repr('\x5c.')
"r'\\.'"
>>> print raw_repr('\x5c.')
r'\.'



-- 
Steven




More information about the Python-list mailing list