+ 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?

24th Jan 2017, 1:48 AM
Jonas Oliveira
Jonas Oliveira - avatar
5 Answers
+ 23
x = 8 print("The number is", x) OR x = 8 print("The number is " + str(x))
24th Jan 2017, 1:53 AM
Kawaii
Kawaii - avatar
+ 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}.'})
24th Jan 2017, 4:05 AM
Don
Don - avatar
+ 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
18th Nov 2018, 12:12 AM
Alon Bohm
Alon Bohm - avatar
+ 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
17th Mar 2019, 8:30 PM
Gan Choon Tad
Gan Choon Tad - avatar
0
you can also do x = 8 print("The number is %s" % x) #or print("The number is {0}".format(str(x)))
26th Jan 2017, 6:58 AM
Mr. M
Mr. M - avatar