Printing string and integer (or float) in the same line | Sololearn: Learn to code for FREE!

+3

Printing string and integer (or float) in the same line

If a define a variable x=8 and need an output like "The number is 8" (in the same line), how could I print the string "The number is" and the variable "x" together? Or the second after the first but in the same line?

1/24/2017 1:48:43 AM

Jonas Oliveira

6 Answers

New Answer

+21

x = 8 print("The number is", x) OR x = 8 print("The number is " + str(x))

+7

If you're using Python 3.6 you can make use of f strings. Which is pretty neat: name = 'Don' print(f'Hey my name is {name}.'})

+4

to sum it up: x = 55 print ("i am" , x) ==> ('i am', 55) print "i am" , x " ==> i am 55 print ("i am " + str(x)) ==> i am 55 print ("i am %s " % x) ==> i am 55 print ("i am {0}".format(str(x))) ==> i am 55

+2

To print, the data type must be the same. E.g. x = 5 1) print (int (x) + 4) >>> 9 ---------------------Valid 2) print (x +4) >>> 9----------------------------Valid 3) print (x + "what" >>> error----------------- Invalid 4) print (x + str("what")) >>> error-----------Invalid 5) print (str (x) + " what") >>> 5 what-------Valid

0

you can also do x = 8 print("The number is %s" % x) #or print("The number is {0}".format(str(x)))