You can use the addition operator “+” to print a new line after a variable in Python. Use newline special character (\n
) to insert new lines in a string.
print(variable + '\n')
The print
function already adds a newline for you, so if you just want to print followed by a newline, do:
print(a)
If the goal is to print the elements of a
each separated by newlines, you can either loop explicitly:
for x in a:
print(x)
or abuse star unpacking to do it as a single statement, using sep
to split outputs into different lines:
print(*a, sep="\n")
If you want a blank line between outputs, not just a line break, add end="\n\n"
to the first two, or change sep
to sep="\n\n"
for the final option.
Python print a new line after variable
A simple example code uses the addition (+) operator to print a new line after a variable.
var1 = "Hello"
my_str = var1 + '\n' + 'John'
print(my_str)
print(type(my_str))
Output:
Print a new line after each item in the list of integers
my_list = [2, 4, 8]
result = '\n'.join(str(num) for num in my_list)
print(result)
Output:
2
4
8
Using a formatted string literal
var1 = "Hello"
my_str = f'{var1}\nJohn'
print(my_str)
Do comment if you have any doubts or suggestions on this Python Print topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.