How to Print on the Same Line in Python
Printing output on the same line is a common formatting requirement in Python.
This guide explores various techniques to achieve this, focusing on the print()
function, iterable unpacking, str.join()
, and combining printing with input on the same line.
Printing on the Same Line with end
Argument
The print()
function's end
argument controls what's printed at the end of the output, defaulting to a newline character (\n
). Setting it to a space (' '
) prints items on the same line, separated by spaces.
my_list = ['tutorial', 'reference', 'com']
for item in my_list:
print(item, end=' ') # Output: tutorial reference com
This method is useful when iterating over an iterable and printing its elements horizontally.
Printing with Iterable Unpacking
The iterable unpacking operator (*
) unpacks an iterable's items as arguments to a function. This provides a concise way to print items on the same line, separated by spaces:
my_list = ['tutorial', 'reference', 'com']
print(*my_list) # Output: tutorial reference com
- The
*
operator unpacks the items inmy_list
as separate arguments toprint()
.
You can control the separator with the sep
argument:
my_list = ['tutorial', 'reference', 'com']
print(*my_list, sep='') # Output: tutorialreferencecom
print(*my_list, sep='-') # Output: tutorial-reference-com
Printing with str.join()
The str.join()
method efficiently concatenates a list of strings into a single string, allowing you to print them on the same line with a separator.
my_list = ['tutorial', 'reference', 'com']
result = ' '.join(my_list)
print(result) # Output: tutorial reference com
The str.join()
method is called on the desired separator string (' '
for a space), and its argument is the list of strings to join.
To print numbers horizontally, convert them to strings:
my_list = [2, 4, 8]
result = ' '.join(str(number) for number in my_list)
print(result) # Output: 2 4 8
Combining print()
and input()
on the Same Line
To print a message and take user input on the same line, pass the prompt directly to the input()
function:
username = input('Enter your username: ')
print(username) # Prints on a new line
If you want to keep both the print()
and input()
on the same line, you can pass a prompt argument to the input function, and print the result on the same line using the sep
and end
arguments:
print(
'Your username is: ',
input('Enter your username: '),
sep='',
end=''
)
Alternatively, you can achieve the same using an f-string.
print(f'Your name is: {input("Enter your name: ")}')