+ 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?
5 Answers
+ 23
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)))
Hot today
BMI calculator code project
0 Votes
SQL
1 Votes
Paint Costs
1 Votes
How to create a border
0 Votes
Overloading + operator
0 Votes