escaping

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Apr 15 22:42:09 EDT 2012


On Sun, 15 Apr 2012 23:07:36 +0200, Kiuhnm wrote:

> This is the behavior I need:
>      path = path.replace('\\', '\\\\')
>      msg = ". {} .. '{}' .. {} .".format(a, path, b)
> Is there a better way?


This works for me:

>>> a = "spam"
>>> b = "ham"
>>> path = r"C:\a\b\c\d\e.txt"
>>> msg = ". %s .. %r .. %s ." % (a, path, b)
>>> print msg
. spam .. 'C:\\a\\b\\c\\d\\e.txt' .. ham .



Another possibility:

>>> print path.encode('string_escape')
C:\\a\\b\\c\\d\\e.txt


-- 
Steven



More information about the Python-list mailing list