[Tutor] help on raw_input()

Kent Johnson kent37 at tds.net
Sat Apr 14 13:36:04 CEST 2007


ammar azif wrote:
> Hi,
> 
> i wanted to get a string from raw_input like this
> 
> raw_input('>')
>  > \n\nsomestring
> 
> but the problem is raw input will return the string
> '\\n\\nsomestring'

This is a bit confusing to talk about because the actual contents of the 
string differ from what is printed. I don't know if you realize that or 
not so I'll start at the beginning.

In [3]: s= raw_input('> ')
 > one\r\ntwo
In [4]: s
Out[4]: 'one\\r\\ntwo'

When the interpreter outputs a string, it outputs it in the form of a 
string constant. Any actual \ in the string is escaped with an extra \. 
The string s contains single \ characters. You can verify this by 
getting the length:
In [5]: len(s)
Out[5]: 10

or by outputting it with print, which just outputs the actual characters:
In [6]: print s
one\r\ntwo

So s does contain the same characters as typed.

 > My question is
 > Are there any function to convert back those string to '\n\nsomestring' ?

You don't want the four literal characters \, r, \, n, you want a 
carriage return / newline combination. raw_input() doesn't interpret 
escape characters but there is a way to convert them:
In [7]: t=s.decode('string_escape')

Now t contains a carriage return / newline instead of the escape characters:
In [8]: t
Out[8]: 'one\r\ntwo'
In [9]: len(t)
Out[9]: 8
In [10]: print t
one
two

Kent


More information about the Tutor mailing list