+ 4

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
8 Antworten
+ 25
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
+ 9
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
+ 5
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
+ 1
You have two options: x = 8 print("The number is", x) Because you can put integers and strings in the same line if you use a comma instead of a plus. OR you can do this: x = 8 print("The number is" + str(x)) Because if you try to put an integer and string in the same line using the plus sign, it will give you an error. However, if you add the "str" bit before putting your "x", it changes your integer to a string. That way they both go together
7th Feb 2023, 12:53 AM
__________________________________________________
__________________________________________________ - avatar
+ 1
In Python, you can print a combination of strings and integers (or floats) in the same line using the print() function. You can achieve this by separating the items you want to print with commas within the print() function. Here's an example: name = "John" age = 30 height = 5.9 print("Name:", name, "Age:", age, "Height:", height) you can run this code here: https://pythondex.com/online-python-compiler
23rd Oct 2023, 9:47 AM
Jarvis Silva
Jarvis Silva - 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