Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use same variable multiple times in print

Tags:

python

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?

like image 385
newbie Avatar asked Feb 11 '23 07:02

newbie


1 Answers

>>> 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
like image 57
John1024 Avatar answered Feb 13 '23 03:02

John1024