How can I print variable and string on same line in Python?
Python is a very versatile language. You may print variables by different methods. I have listed below five methods. You may use them according to your convenience.
Example:
a = 1
b = 'ball'
Method 1:
print('I have %d %s' % (a, b))
Method 2:
print('I have', a, b)
Method 3:
print('I have {} {}'.format(a, b))
Method 4:
print('I have ' + str(a) + ' ' + b)
Method 5:
print(f'I have {a} {b}')
The output would be:
I have 1 ball
Two more
The First one
>>> births = str(5)
>>> print("there are " + births + " births.")
there are 5 births.
When adding strings, they concatenate.
The Second One
Also the format
(Python 2.6 and newer) method of strings is probably the standard way:
>>> births = str(5)
>>>
>>> print("there are {} births.".format(births))
there are 5 births.
This format
method can be used with lists as well
>>> format_list = ['five', 'three']
>>> # * unpacks the list:
>>> print("there are {} births and {} deaths".format(*format_list))
there are five births and three deaths
or dictionaries
>>> format_dictionary = {'births': 'five', 'deaths': 'three'}
>>> # ** unpacks the dictionary
>>> print("there are {births} births, and {deaths} deaths".format(**format_dictionary))
there are five births, and three deaths
Edit:
Its 2022 and python3 has f strings now.
>>> x = 15
>>> f"there are {x} births"
'there are 15 births'
Use ,
to separate strings and variables while printing:
print("If there was a birth every 7 seconds, there would be: ", births, "births")
,
in print function separates the items by a single space:
>>> print("foo", "bar", "spam")
foo bar spam
or better use string formatting:
print("If there was a birth every 7 seconds, there would be: {} births".format(births))
String formatting is much more powerful and allows you to do some other things as well, like padding, fill, alignment, width, set precision, etc.
>>> print("{:d} {:03d} {:>20f}".format(1, 2, 1.1))
1 002 1.100000
^^^
0's padded to 2
Demo:
>>> births = 4
>>> print("If there was a birth every 7 seconds, there would be: ", births, "births")
If there was a birth every 7 seconds, there would be: 4 births
# formatting
>>> print("If there was a birth every 7 seconds, there would be: {} births".format(births))
If there was a birth every 7 seconds, there would be: 4 births