[Tutor] a question regarding os.system()

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Thu, 30 Aug 2001 01:11:30 -0700 (PDT)


On Thu, 30 Aug 2001, Bruce Sass wrote:

> On Thu, 30 Aug 2001, Haiyang wrote:
> > I know that we can use os.system() to lauch applications.
> > Say, I want to use notepad to open a file - data.txt
> > I should do
> > os.system('notepad data.txt')
> >
> > BUT what if  the string 'data.txt' is stored in a variable, how can use
> > notepad to open it?
> >
> > file='c:\data\data.txt'
> > os.system('notepad     and What?
> 
> os.system('notepad %s' % file)


Another way to do it is to stick together strings with addition:

###
>>> command = "notepad"
>>> file = "data.txt"
>>> command + file
'notepaddata.txt'
###

... although it does require a little extra effort to make sure we don't
squeeze the words together:

###
>>> command + ' ' + file
'notepad data.txt'
###



Bruce's approach to building up strings is called "String Formatting", and
we can think of it sorta like Madlibs: string formatting will substitute
in strings whereever it sees a "%s".



In fact, there's a variation on this formatting that looks very much like
Madlibs:

###
>>> story = """Once upon a %(noun1)s, there lived a %(adjective1)s
... %(noun2)s, and the %(noun1)s %(verb1)sed it every day."""
>>> story % { 'noun1' : 'Tim',
...           'adjective1' : 'holy',
...           'noun2' : 'Hand Grenade',
...           'verb1' : 'bless' }
'Once upon a Tim, there lived a holy\nHand Grenade, and the Tim blessed it
every day.'
###


You can find more about in the "Fancier Output Formatting" section of the
tutorial here:

http://www.python.org/doc/current/tut/node9.html#SECTION009100000000000000000



Also, there are some formal docs here:

    http://www.python.org/doc/current/lib/typesseq-strings.html

if you need to go to sleep anytime soon.  *grin*


Talk to you later!