9

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'
Community
  • 1
  • 1
Bite code
  • 578,959
  • 113
  • 301
  • 329
  • Are you sure it won't be interpreted as a line break? Do you mean repr(thestring) is '\n test' or "'\n test'"? – AdamKG Jan 16 '12 at 12:05
  • It can't be interpreted as a line break. Line breaks are only interpreted in a string litteral, in the source code. This input comes from the web, if you want to have a code equivalent, you need to write a litteral with the 'r' prefix. – Bite code Jan 16 '12 at 12:08
  • What do you mean by isn't interpreted as a line break? Are you maybe getting `'\\n'` instead? – jcollado Jan 16 '12 at 12:08
  • I can not delete it because it has answers. I'm voting to close. – Bite code Jan 16 '12 at 12:21

1 Answers1

15

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

Community
  • 1
  • 1
nos
  • 223,662
  • 58
  • 417
  • 506