print string as raw string

Miles semanticist at gmail.com
Tue Feb 17 18:24:35 EST 2009


On Tue, Feb 17, 2009 at 2:01 PM, Scott David Daniels 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 "\\."  ...
>
> ...
> 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.

It seems to me that a raw_repr should only be required to be able to
encode strings that are representable as raw strings in the first
place.  Here's mine:

def raw_repr(s):
    if s and s[-1] == '\\':
        raise ValueError('No raw string representation; '
                         'string ends in backslash')
    # If you want to test for control and non-ASCII characters to raise
    # an exception, that's up to you
    quote = None
    if '\n' not in s:
        if "'" not in s:
            quote = "'"
        elif '"' not in s:
            quote = '"'
    if not quote:
        if "'''" not in s:
            quote = "'''"
        elif '"""' not in s:
            quote = '"""'
    if not quote:
        raise ValueError('No raw string representation; '
                         'string contains unescapable quote characters')
    return 'r' + quote + s + quote

>>> print raw_repr(r"1\2'3\n")
r"1\2'3\n"
>>> print raw_repr(r'''"What's up," he said.''')
r'''"What's up," he said.'''
>>> # valid raw string, left as an exercise for the reader:
... print raw_repr(r'"""'"'''") # ;)
Traceback (most recent call last):
  File "<stdin>", line 2, in ?
  File "<stdin>", line 19, in raw_repr
ValueError: No raw string representation; string contains unescapable
quote characters

-Miles



More information about the Python-list mailing list