simple string question

Niklas Norrthon niklas.norrthon at hotmail.com
Mon Sep 7 04:54:09 EDT 2009


On 7 Sep, 07:29, "jwither" <jwit... at sxder4kmju.com> wrote:
> Given a string (read from a file) which contains raw escape sequences,
> (specifically, slash n), what is the best way to convert that to a parsed
> string, where the escape sequence has been replaced (specifically, by a
> NEWLINE token)?
>
> James Withers

Others have answered how to replace '\\n' with '\n'. For a more
general approach which will handle all string escape sequences allowed
in python (including '\xdd' and similar), python's eval can be used:

>>> quoted_string = "'hello\\nworld\\x21\\tand\\tgood\\040\\x47ood bye!'"
>>> print quoted_string
'hello\nworld\x21\tAnd\tgood\040\x47ood bye!'
>>> print eval('str(%s)' % quoted_string)
hello
world!	And	good Good bye!

If the string isn't quoted just enclosed it in quotes first:
>>> unquoted_string = 'hello\\nworld\\x21\\tand\\tgood\\040\\x47ood bye!'
>>> print unquoted_string
hello\nworld\x21\tAnd\tgood\040\x47ood bye!
>>> print eval('str("%s")' % unquoted_string)
hello
world!	And	good Good bye!

/Niklas Norrthon



More information about the Python-list mailing list