[Tutor] question on string
dyoo at hkn.eecs.berkeley.edu
Mon Aug 1 21:48:26 CEST 2005
On Mon, 1 Aug 2005, Kent Johnson wrote:
> > I would like to construct some string objects using the cprintf-style
> > format:
> > command_string = "diff -u %s %s > %s.patch" % ( src, dst, file )
> > Of course it is illegal in python but I couldn't figure out a way to
> > construct strings with that kind of formatting and substitution.
> Actually that is correct as written! (though 'file' is a poor choice of
> variable name as it shadows the built-in file() function...)
Just as a side note, building command strings like this is usually not a
good idea, just because of issues like shell quotation.
Unfortunately, there are a lot of examples on the web that do use string
interpolation to build up command lines, but there is usually a better
way: Python comes with a subprocess module which can take a list of
arguments. For example:
>>> import subprocess
>>> p = subprocess.Popen(['wc', '-l', '/usr/share/dict/words'],
The advantage of passing a list instead of a formatted string here is that
we don't have to worry if our files contains spaces in their names.
Hope this helps!
More information about the Tutor