Python String - Append Newline


Python String - Append Newline

To append a newline to a string in Python, you can use string concatenation or formatted strings.

In this tutorial, we shall go through these two approaches, and learn how to append a newline to a string with examples.

1. Append newline to string using string concatenation in Python

Given a string in x . We have to append the number in n to the string in x using string concatenation operator +.

Use string concatenation operator + and pass the given string x as left operand and the new line character "\n" as second operand.

x + "\n"

The above expression returns a new string, where the string in x is appended with a newline.

Python Program

# Given string
x = "apple"

# Append newline to the string
result = x + "\n"

# Print the result
print(result)

Output

apple

If you print the resulting string to the output, please note that a new empty line appears after the original string.

2. Append newline to string using formatted strings in Python

Given a string in x . We have to append the number in n to the string in x using formatted strings.

Use the following formatted string expression to append newline to the string x.

f"{x}\n"

The above expression returns a new string, where the string in x is appended with a newline.

Python Program

# Given string
x = "apple"

# Append newline to the string
result = f"{x}\n"

# Print the result
print(result)

Output

apple

Summary

In this Python Strings tutorial, we learned how to append a newline to a string. In the first approach, we used string concatenation operator. In the second approach, we used formatted string. We have covered programs for each of these approaches and learned how to append a newline to a string in Python.