Add newline character after Input message in Python


Borislav Hadzhiev

Last updated: Aug 24, 2022


Photo from Unsplash

Add newline character after Input message in Python #

Use the \n character to add a newline character after an input message, e.g. user_input = input('Enter a word:\n'). The \n character will add a newline character right after the input message.
user_input = input('Enter a word:\n') print(user_input)

add newline character after input message

The \n character adds a newline right after the input message.

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

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

Note that the input() function is guaranteed to return a string, even if the user enters a number.

If you need to convert the value to a number, use the int() class.
user_input = '' try: user_input = int(input('Enter an integer\n')) except ValueError: print('Invalid integer') print(user_input)

If you have the input message stored in a variable, use the addition (+) operator to append the newline character to the message.
message = 'Enter a word:' user_input = input(message + '\n') print(user_input)

The code snippet above achieves the same result.

You can also use a formatted string literal.
message = 'Enter a word:' user_input = input(f'{message}\n') print(user_input)

Formatted string literals (f-strings) let us include expressions inside of a string by prefixing the string with f.
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.