Backslash to forward in unicode string in Python -


i have spreadsheet dates, encoded strings in format "dd\mm\yyyy", 08\09\2014. function use returns data unicode, , use python 2.7. so, start with:

> data_prob_raw 08\09\2014 

to convert string datetime object (datetime.parser.parse()) need string without '\', don't find way remove or substitute problematic character '/'. tried unicode codes:

data_prob_raw=data_prob_raw.replace(r'\x81', '/201') data_prob_raw=data_prob_raw.replace(u'\x81', '/201') 

and string:

data_prob_raw=data_prob_raw.replace('\201','/201') 

but doesn't change anything:

08\09\2014 

decoding string:

data_prob_raw=data_raw_unic.encode('ascii') 

but \201 goes uver 128 ascii chars:

unicodedecodeerror: 'ascii' codec can't decode byte 0x81 in position 0: ordinal not in range(128) 

how can solve problem?

when read data file python should escaped string.

i have file called test.txt contents 01\01\2010

>>> open(r'c:\users\john\desktop\test.txt') f:         s = f.read()  >>> s '01\\01\\2010' >>> s.replace('\\', '/') '01/01/2010' 

and have no problem using .replace on string. might happening creating variable directly, test functionality, , assigning data_prob_raw='08\09\2014' when should testing either data_prob_raw='08\\09\\2014' or reading date in file.

as zondo suggested can use raw stings so; data_prob_raw=r'08\09\2014'. notice preceding r, r tells python treat backslashes literal backslashes instead of parsing escape characters.


Comments