Ethan L
Ethan L

Reputation: 23

How do I print a variable inside ""?

How do I print a variable within ""? for example;

a = "test"
print"this is a (how do I input 'a' here?)"

Upvotes: 1

Views: 100

Answers (3)

sypy
sypy

Reputation: 1

You can use the plus operator:

a = "test"
print"this is a " + a

See: https://pythonspot.com/python-strings/

Upvotes: 0

idjaw
idjaw

Reputation: 26580

You should read the print tutorial:

But what you are looking to do is this:

print("this is a {} here?".format(a))

If you are looking to put multiple variables in your string, you can simply do this:

print("this is a {0} here and {1} and also {2}?".format(a, b, c))

You could actually just write the line like this without the number specifications:

print("this is a {} here and {} and also {}?".format(a, b, c))

Being explicit with the numbers would be best if you were looking to re-order the placement of the arguments in the string, like this:

print("this is a {2} here and {0} and also {1}?".format(a, b, c))

So, in the above example, first string would be c, then a, then b.

For your particular case where you are trying to add quotes in your string, there are different ways you can do this. If you want double quotes, you can wrap with single quotes:

print('this is a "{2}" here and "{0}" and also "{1}"?'.format(a, b, c))

If you want single quotes, wrap with double quotes:

print("this is a '{2}' here and '{0}' and also '{1}'?".format(a, b, c))

Finally, there is the triple single quote:

print('''this is a '{2}' here and '{0}' and also '{1}'?'''.format(a, b, c))

Mix whichever type of quote:

print('''this is a "{2}" here and "{0}" and also '{1}'?'''.format(a, b, c))

Upvotes: 4

Tamil Selvan C
Tamil Selvan C

Reputation: 20219

Use (Python 3)

print("this is a (how do I input ", a , "here?)")

See: https://docs.python.org/3.0/whatsnew/3.0.html

For older version use

print "this is a (how do I input '%s' here?)" % a

See http://learnpythonthehardway.org/book/ex5.html

Upvotes: 0

Related Questions