+ 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?
8 Respostas
+ 25
x = 8
print("The number is", x)
OR
x = 8
print("The number is " + str(x))
+ 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}.'})
+ 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
+ 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
+ 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
+ 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
0
you can also do
x = 8
print("The number is %s" % x)
#or
print("The number is {0}".format(str(x)))