A Python quoting irritationI was writing code today where I needed to turn a single backslash ('\') into two backlashes ('\\') in order to quote it (so that the shell wouldn't eat it, through a combination of annoyances). My first attempt was: s = s.replace(r"\", r"\\") To my surprise, this gave me an error, and a peculiar one: Python
reported Ultimately, this is because Python uses backslash in strings for two
separate jobs: quoting end of string characters, and introducing special
characters like Where things get really confusing is the handling of ' So the ultimate answer I wound up with is:
You can write the second string as (This is all actually documented in the string literal section of the reference manual. If it is covered in the tutorial, I read it sufficiently long ago to have forgotten it.) All of this (coupled with wrestling with shell quoting, which is how I wound up dealing with this) has reminded me of how much I hate complicated quoting schemes and the need for quoting in general. (3 comments.)
|
These are my WanderingThoughts GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |