[Tutor] Variables in os.system() [string formatting]

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Wed, 23 Jan 2002 14:10:31 -0800 (PST)

On Wed, 23 Jan 2002, Kelly, Phelim wrote:

>        At the moment I'm using the os.system() functionality in a
> python program to output a command to the command line as follows:
> os.system("<command>"+variable)
> The variable is pre-defined and is appended to the text in <command>.
> I need to be able to add another variable, but have it in the middle
> of the <command>, not just at the end, something like....
> os.system("<start of command>"+variable1"<end of command>"+variable2)

Hi Kelly,

String concatenation is a good approach; I believe this should work.  
However, we need to be careful here:

> os.system("<start of command>"+variable1"<end of command>"+variable2)

The code here is missing a plus sign between the 'variable1' variable and
the rest of the string, so you may get a SyntaxError out of this.

Another thing that might bite us is that string concatenation between two
things works only if both are strings:

>>> "hello" + "world"
>>> "the magic number is " + 42
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: cannot add type "int" to string
>>> "the magic number is " + str(42)
'the magic number is 42'

The last example shows that we can bend 42 into a string, and that'll
allow the concatenation to work.

Another approach is to use string formatting to fill in the blanks:

    cmd = "<start of command>%(var1)s<end ofcommand>%(var2)s"
    cmd = cmd % { 'var1' : variable1,
                  'var2' : variable2 }

The important parts about string formatting is the "%(var1)s" and
"%(var2)s" stuff.  These are called "format strings", and when we use the
string formatting operator '%', Python will substitute the format string
with the values we want.  Think Madlibs, and you'll get the general idea.

Here's an example of string formatting in the interpreter:

>>> "%(person)s is working on a program" % { 'person' : 'tidus' }
'tidus is working on a program'
>>> '%(person1)s and %(person2)s %(verbed)s' % { 'person1': 'rikku',
...                                              'person2': 'auron',
...                                              'verbed': 'laughed' }
'rikku and auron laughed'

String formatting is often nicer than doing a bunch of string
concatenations, because it allows us to separate the form of the output
from the particular values we're plugging.  (It's also a bit more
efficient for the computer.)  String formatting is especially useful when
we're doing things like templated forms or HTML generation.

There's some examples of it in action in the Python tutorial.  You might
want to take a look at the "Fancier Output Formatting" chapter for more


and most Python tutorials should cover this topic since it is very useful.

Can you give us a concrete example of a command in this form?  That may
help us tailor a useful example that uses string formatting.