EOL - scanning single-quoted string

Christopher T King squirrel at WPI.EDU
Wed Aug 4 09:53:09 EDT 2004


On Wed, 4 Aug 2004, Ajay wrote:

> i got the escape character bit, but i still get an error
> >>> str='/My Documents/um_ajay.xml'
> >>> re.subn('/', '\\', str)

Ah... regex quoting issues.  The '\\' makes a single '\' appear in the 
string, but being a regex, a single '\' in a string is again interpreted 
as a backslash.  You will either have to write '\\\\' or use a raw string, 
r'\\'.  Raw strings pass backslashes untouched, so you only need to 
backslash it once for the regex.

However, the best solution for your problem is not to use regexes, but to 
use the os.path module:

>>> from os.path import normpath, abspath
>>> str = '/My Documents/um_ajay.xml'
>>> normpath(str)
'\\My Documents\\um_ajay.xml'
>>> abspath(str)
'C:\\My Documents\\um_ajay.xml'

normpath() 'tidies up' the path, a task which includes correcting path 
seperators, amoung other things.  abspath() does the same thing as 
normpath(), but also resolves relative paths into absolute ones.  Always 
look to os.path when doing anything involving paths; it probably has the 
function you want, and is portable across platforms.




More information about the Python-list mailing list