Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Python module to parse line break notation in a raw string? [duplicate]

Possible Duplicate:
Process escape sequences in a string in Python

If I get this string, for example from a web form:

'\n test'

The '\n' notation won't be interpreted as a line break. How an I parse this string so it becomes a line break?

Of course I can use replace, split, re, etc, to do it manually.

But maybe there is a module for that, since I don't want to be forced to deal with all the \something notations manually.

I tried to turn it into bytes then use str as a construtor but that doesn't work:

>>> str(io.BytesIO(ur'\n'.encode('utf-8')).read())
'\\n'
like image 946
e-satis Avatar asked Jan 16 '12 12:01

e-satis


1 Answers

Use .decode('string_escape')

>>> print "foo\\nbar\\n\\tbaz"
foo\nbar\n\tbaz
>>> print "foo\\nbar\\n\\tbaz".decode('string_escape')
foo
bar
        baz

As I'm typing in code, the above have to escape the \ to make the string contain the 2 characters \n

Edit: actually this is a duplicate of Process escape sequences in a string in Python

like image 151
nos Avatar answered Nov 15 '22 14:11

nos