Parsing strings (\n and \\)

Jonathan Hogg jonathan at onegoodidea.com
Wed Jun 26 04:20:55 EDT 2002


On 25/6/2002 17:01, in article lt0S8.45025$n4.10623651 at newsc.telia.net,
"Fredrik Lundh" <fredrik at pythonware.com> wrote:

>>>> UNPARSED = "__import__('os').system('echo dream on!')"
>>>> PARSED = eval(UNPARSED, {}, {})
> dream on!

OK. Moving on from the arguments against using 'eval', how about:

>>> import re
>>> 
>>> ESCAPE_CRE = re.compile( r'\\(.)' )
>>> ESCAPE_SUBS = { 'n': '\n', 't': '\t' }
>>> 
>>> def replace_match( m ):
...     c = m.group( 1 )
...     return ESCAPE_SUBS.get( c, c )
... 
>>> def replace_escapes( s ):
...     return ESCAPE_CRE.sub( replace_match, s )
... 
>>> replace_escapes( '\\\\this is a \\test\\n' )
'\\this is a \test\n'
>>> print _
\this is a      est

>>> 

Obviously this deals only with the easiest cases, but extending it to handle
octal codes and any other special cases shouldn't be too hard (change the
regular expression and put some if...then...else magic into replace_match).

Jonathan




More information about the Python-list mailing list