building strings from variables
ak at silmarill.org
Thu Oct 5 18:50:19 CEST 2006
Gal Diskin wrote:
> Following a discussion with an associate at work about various ways to
> build strings from variables in python, I'd like to hear your opinions
> and preferred methods. The methods we discussed are:
> 1. some_string = "cd %s ; %s %d %s %s" % ( working_dir, ssh_cmd,
> some_count, some_param1, some_param2)
> 2. import string
> template = string.Template("cd $dir ; $cmd $count $param1
> some_string = template.substitute(dict(dir=working_dir,
> here you can use a couple of nice tricks by using class.__dict__ and
> globals() \ locals() dictionaries.
> 3. some_string = "cd "+working_dir+" ; "+ssh_cmd+ "
> "+str(some_count)+" "+some_param1+" "+some_param2
> (all these are supposed to produce the same strings)
> Which methods do you know of \ prefer \ think is better because...?
> I will appreciate any opinions about the matter.
My opinion is that 1st method is the best. It's both very readable and
easy to write. 2nd way is too involved, and 3rd way is both hard to
read and difficult to compose. Another useful variant of method #1 is
to do this: %(varname)s ..." % globals()
More information about the Python-list