In PHP you can do something like this to accomplish variable substitution.
1 2 3 4 5 | $foo = 'Foo';
echo "I think I have some $foo on my shoe";
# Output
# I think I have some Foo on my shoe
|
A colleague who uses Groovy a lot asked me if Python had an equivalent, too.
So, I did some research and couldn’t find a good solution.
There was this
But this is heavier than I wanted, certainly useful but not for this particular 1-liner solution I was looking for
1 2 3 4 5 6 7 | import string
foo_style = string.Template('Did you just drop that $huhwha?')
print foo_style % {'huhwha': 'Foo'}
# Did you just drop that Foo?
|
And this
But it has it’s problems, I don’t really want to use a C-style print formatting here.
1 2 3 4 5 | foo = "Foo"
print 'That is the smelliest %s that I have smelled' % foo
# That is the smelliest Foo that I have smelled
|
How about this
I like this the best.
1 2 3 4 5 | foo = 'Foo'
print '%(foo)s! Did I scare you?' % locals()
# Foo! Did I scare you?
|
What happens here is that locals() is a dictionary of all local variables. A dictionary is exactly what that string
format needs to do it’s job. Works out quite nice. And when you decide later on that you want to use another dictionary of key values
instead of locals you can switch it out pretty easy.
And just one more tip
This got me the first time. You need to format the variable reference like %(VARNAME)s.
1 2 3 4 5 6 7 | foo = 'Foo by itself'
# The short way
print '%s' % foo
# And to use a dictionary
print '%(foo)s' % { 'foo': foo }
|