using python variables inside quotes
Jeff Collins
collins at seal.aero.org
Tue Mar 14 20:13:06 EST 2000
lewst writes:
> Greetings,
>
> This is a simple question, so please excuse, but I am slowly learning
> Python by trying to rewrite all my Perl scripts. Thus far I like it
> much better than Perl, but a small matter has me stumped.
>
> My question deals with using variables inside quotes. Take this
> sample program for example:
>
> #!/usr/bin/env python
>
> import os, random
>
> imgdir = "/home/lewst/images/"
For sake of portability, you may wish to write:
imgdir = os.path.join("home","lewst","images")
> piclist = os.listdir(imgdir)
>
> chosenpic = imgdir + random.choice(piclist)
chosenpic = os.path.join(imgdir, random.choice(piclist))
> os.system("xv %s &" % chosenpic)
I tend to like this better than the perl way. When you become more
acustomed to python, the concept of embedding variables in a string
just won't seem natural.
Other possibilities:
1)
os.system(string.join(("xv", chosenpic, "&")))
2) <more complex and ugly, but provides a perl flavor>
os.system("xv %(chosenpic)s &" % locals())
3) custom function
def xv(pic):
os.system('xv %s &' % pic)
xv(chosenpic)
>
> This script displays a random image from a directory full of images
> using the "xv" image manipulation program.
>
> Is there a simpler way to access the `chosenpic' variable within the
> os.system() call? At first I tried the following:
>
> os.system("xv chosenpic &")
>
> This didn't work, because it is looking for the literal "chosenpic"
> instead of the name of one of my images.
>
> In Perl, I could use the following:
>
> system("xv $chosenpic &");
>
> Perl recognizes the `$' as a variable. Since in Python variables are
> not declared with punctuation marks like this, it is not as easy to
> distinguish them from regular words.
>
> Have I missed something trivial?
>
> (Please CC: me on followups)
>
> __________________________________________________
> Do You Yahoo!?
> Talk to your friends online with Yahoo! Messenger.
> http://im.yahoo.com
>
> --
> http://www.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list