In Python if I want to use a variable in string while printing I do the following:
name = "newbie"
site = "Stack Overflow"
print("I, a %s, find %s very useful" % (name, site))
If I want to print "I, a newbie, find Stack Overflow to be very very very useful'
and substitute 'very'
by a variable name, how can I do that, while still using the name
and site
variables?
>>> print("I a {0} find {1} {2} {2} {2} {2} useful".format(name, site, 'very'))
I a newbie find stackoverflow very very very very useful
Or, using names:
>>> a='very'
>>> print("I a {name} find {site} {a} {a} {a} {a} useful".format(name=name, site=site, a=a))
I a newbie find stackoverflow very very very very useful
Or, using the local dictionary:
>>> print("I a {name} find {site} {a} {a} {a} {a} useful".format(**locals()))
I a newbie find stackoverflow very very very very useful
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With