king
king

Reputation: 1344

how do you put a period right next to a variable in python?

im new to python so this will be really easy for you guys i'm sure.

i wrote a simple thing in python, but i was curious how to put a period next to the variable i am using, i will show you here:

i = 5
print "i is equal to", i,"."

i run it and it comes out like this:

i is equal to 5 .

how do you make it so the (period) is right next to the 5, like "i is equal to 5."

i tried searching for this but i feel like it too simple i can't find it lol and i don't know what things are called exactly, thanks.

Upvotes: 0

Views: 14541

Answers (3)

Kitti C
Kitti C

Reputation: 1

print "i is equal to", str(i) + "."

You can also just use the str() function at the very end, no need to convert everything to strings. Easier when you have more variables and text in the print line.

Example:

print (a,"+",b,"is equal to", str(a+b) + ".")

vs

print (str(a)+" + "+str(b)+" is equal to "+str(i)+".")

Upvotes: 0

bradley.ayers
bradley.ayers

Reputation: 38382

Use string formatting:

print "i is equal to %d." % i

As of Python 2.6, strings have a .format() function that can alternatively be used:

>>> print "i is equal to {}".format(i)
i is equal to 5

It's useful if you have a placeholder that's used multiple times in the format string:

>>> print "i={0}, a.k.a. 'i is equal to {0}.'".format(i)
i=5, a.k.a. 'i is equal to 5.'

Upvotes: 7

Yunzhi Ma
Yunzhi Ma

Reputation: 672

You can also concatenate like this,

print "i is equal to " + str(i) + "."

Upvotes: 7

Related Questions