How to Create a String with Newline in Python

In this Python tutorial, we will learn how to create a string with newline characters in Python. We will be using three different methods to achieve this: using escape sequences, triple quotes, and the join() method.

Create a String with Newline in Python

Now, let us see the 3 different ways to create a string with newline in Python.

Method 1: Escape Sequences

To add a newline character to a string in Python, you can use the escape sequence \n. This sequence represents a newline character, which causes the string to break and start a new line when displayed.

# Using escape sequences to create a string with newline
cities = "New York\nLos Angeles\nChicago\nHouston\nPhoenix"

print(cities)

Output:

New York
Los Angeles
Chicago
Houston
Phoenix

You can see the complete code:

Create a string with newline in Python
Create a string with newline in Python

This is how to create a string with newline in Python using escape sequences.

Method 2: Triple Quotes

Another way to create a string with newlines in Python is by using triple quotes (''' or """). With triple quotes, you can span your string across multiple lines, and the newlines will be preserved when the string is displayed.

# Using triple quotes to create a string with newline
cities = """New York
Los Angeles
Chicago
Houston
Phoenix"""

print(cities)

Output:

New York
Los Angeles
Chicago
Houston
Phoenix

This is how to create a string with newline in Python using triple quotes.

Method 3: Using the join() Method

We can also use the join() method to create a string with newline in Python. The join() method is used to concatenate strings with a specified delimiter. In this case, we can use it to create a string with newline characters in Python.

# Using join() method to create a string with newline in Python
cities_list = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
cities = "\n".join(cities_list)

print(cities)

Output:

New York
Los Angeles
Chicago
Houston
Phoenix
How to create a string with newline in Python
How to create a string with newline in Python

This is how to create a string with newline in Python using the join() method.

Conclusion

We have explored three methods for creating strings with newline characters in Python: using escape sequences, triple quotes, and the join() method. The escape sequence method utilizes \n to insert newline characters within the string. The triple quotes method allows you to directly write multiline strings, preserving the newline characters. Lastly, the join() method concatenates a list of strings with the specified delimiter, which in this case, is the newline character.

You may also like: