unescape escapes in strings

MRAB google at mrabarnett.plus.com
Mon Feb 23 19:22:51 CET 2009


bvdp wrote:
> 
> When reading lines of data from a file in the from (no quotes!)
> 
>     foo\x20bar
> 
> and I assign to a variable in a line line like:
> 
>  f = file('infile', 'r')
>  for a in f:
>     print a
> 
> the string is read in as string with the literal characters 'f', 'o' ... 
> 'x' , '2' ...
> 
> as compared to an assignment like:
> 
>  a="foo\x20bar"
> 
> which is identical to
> 
> a="foo bar"
> 
> Okay, so far ... I think this is what I want since my program is using 
> space characters as delimiters and I'm trying to use the \x20 notation 
> to avoid splitting.
> 
> But, now the problem. When I finally assign the string with the \x20 to 
> a variable the literals are still there. And here I really want them all 
> nicely converted to the desired values.
> 
> So, the question is: is there an "unescape()" for strings so that 
> "foo\x20bar" is converted to "foo bar"????
> 
 >>> a = r"foo\x20bar"
 >>> print a
foo\x20bar
 >>> a = a.decode("string-escape")
 >>> print a
foo bar




More information about the Python-list mailing list