[Tutor] Reading escaped characters from a file

Kent Johnson kent37 at tds.net
Sat Oct 14 20:21:42 CEST 2006


David Heiser wrote:
>  
> I have code that uses variables to hold escaped characters like "\n" or 
> "\03". As long as the assignment is done within the code, like 
> self.crChar = "\n", there is no problem. But When I try to read the 
> same character string from a text file and assign it, the string is seen 
> as just a string of characters instead of an escape sequence, and the 
> program fails.
>  
> I read the "parameter = value" pairs, like "crChar = \n", from an ASCII 
> file and store them in a dictionary; "parameterDict[parameter] = value". 
> Then I assign the value to the variable using "self.crChar = 
> parameterDict["crChar"]. When I print "self.crChar", it displays "\\n 
> <file://\\n>" and it doesn't behave like a carriage return.

You can use the 'string_escape' codec to translate literal backslash 
escapes to the special characters the escapes represent:

In [5]: s='this is not a newline\\n'

In [6]: s.decode('string_escape')
Out[6]: 'this is not a newline\n'

In [7]: s
Out[7]: 'this is not a newline\\n'

See the difference?

Kent



More information about the Tutor mailing list