How can I print variable and string on same line in Python?
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
Printing strings and variables on the same line
You want to combine the two lists into one:
for (h1, s1), (h2, s2) in combinations(zip(header, sequence), 2):
if s1[start:stop] == s2[start:stop]:
print h1, h2, "are concurrent"
else:
print h1, h2, "are not concurrent"
or to reduce duplicate code:
for (h1, s1), (h2, s2) in combinations(zip(header, sequence), 2):
concurrent = s1[start:stop] == s2[start:stop]
print "{} and {} are{} concurrent".format(h1, h2, "" if concurrent else " not")
Python 3: How do I add input and a string to the same line?
The function input() takes in a string to print so you can do this:
name = input("What is your name? ")
And it will print the string before taking input without adding a newline
Printing multiple variables in a separate lines using a single print
In python3:
print(string1, string2, sep='\n')
In python2:
print string1 + '\n' + string2
... or from __future__ import print_function
and use python3's print
Since my first answer, OP has edited the question with a variable type change. Updating answer for the updated question:
If you have some integers, namely int1
and int2
:
Python 3:
print(int1, int2, sep='\n')
Python 2:
print str(int1) + '\n' + str(int2)
or
from __future__ import print_function
print(int1, int2, sep='\n')
or
print '\n'.join([str(i) for i in [int1, int2]])
Related Topics
Django: Deploying an Application on Heroku with SQLite3 as the Database
Flask Application Traceback Doesn't Show Up in Server Log
Connecting Slots and Signals in Pyqt4 in a Loop
Inverting a Dictionary with List Values
How to Change an Image Size in Pygame
Error Message: 'Chromedriver' Executable Needs to Be Path
Pyinstaller Unable to Access Data Folder
Finding What Methods a Python Object Has
Explaining Python's '_Enter_' and '_Exit_'
Python Image Library Fails with Message "Decoder Jpeg Not Available" - Pil
How to Set the Current Working Directory
How to Create Nested Dict in Python