raw strings
Bengt Richter
bokr at oz.net
Tue Oct 8 23:44:06 EDT 2002
On 8 Oct 2002 14:28:30 -0700, mis6 at pitt.edu (Michele Simionato) wrote:
>Is there a function which converts a string in a raw string ?
>
>I mean: if for instance
>
>>>> s='\*hello\*\n'
>
>I want a function raw_string such that
>
>>>> rs=raw_string(s)
>
>is equal to r'\*hello\*\n'.
>
>I tried with
>
>raw_string=lambda s: repr(s)[1:-1]
>
>but doesn't work since the '\*' are escaped to '\\*' whereas r'\*'='\*'.
>
>There must be an internal function doing what I want, but I don't find it.
>
No guarantees, but does this do what you want?
>>> def raw_string(s):
... return "r'%s'" % ''.join(
... [(x,`x`[1:-1],'\\')[`x`[1:].startswith('\\')+(x=='\\')] for x in s]
... )
...
>>> s='\*hello\*\n'
>>> print raw_string(s)
r'\*hello\*\n'
>>> r=r'\*hello\*\n'
>>> print raw_string(r)
r'\*hello\*\n'
Regards,
Bengt Richter
More information about the Python-list
mailing list