How to print() and input() on the same line in Python

avatar

Borislav Hadzhiev

Last updated: Aug 26, 2022

banner

Photo from Unsplash

How to print() and input() on the same line in Python #

Pass a string to the input() function to have a print statement and input on the same line, e.g. username = input('Enter your username: '). The input() function takes a prompt string and prints it to standard output without a trailing newline.

main.py
# ✅ print input message on same line username = input('Enter your username: ') print(username) # ---------------------------------- # ✅ use print() and input() without separator and newline character print( 'Your username is: ', input('Enter your username: '), sep='', end='' )

In the first example, we passed a prompt string to the input() function.

print and input on same line

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

main.py
s = input('Enter your name: ') print(s)

The function then reads the line from input, converts it to a string and returns the result.

You can also use the print() function before or after the input() function.

main.py
print('this runs before') user_input = input('Enter your username: ') print('this runs after')

If you use the print() function instead of the prompt argument, the print statement is printed on a separate line.

main.py
print('Enter your name: ') s = input() print(s)

print input separate

If you want to call the print() function with multiple arguments without a separator, set the sep and end keyword arguments to empty strings.

main.py
print( 'Your username is: ', input('Enter your username: '), sep='', end='' )

print input sep end

The sep argument is the separator between the arguments we pass to print().

By default, the argument is set to a space.

main.py
print('a', 'b', 'c') # 👉️ 'a b c' print('a', 'b', 'c', sep='') # 👉️ 'abc'

The end argument is printed at the end of the message.

By default, end is set to a newline character (\n).

main.py
print('a', 'b', 'c') # 👉️ 'a b c\n' print('a', 'b', 'c', end='') # 👉️ 'a b c'

You can also use a formatted string literal to print multiple arguments on the same line.

main.py
print(f'Your name is: {input("Enter your name: ")}')

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.

main.py
my_str = 'is subscribed:' my_bool = True result = f'{my_str} {my_bool}' print(result) # 👉️ is subscribed: True

Make sure to wrap expressions in curly braces - {expression}.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.