How to Split a String Into Multiple Lines in Python

Splitting a string into multiple lines in Python is a crucial task that can come in handy in many programming scenarios, such as reading data from a file or creating a specific format for user output.

Python provides several ways to accomplish this task. In this tutorial, we will show you different methods on how you can split a string into multiple lines in Python.

Method 1: Using Escape Sequence

The escape sequence \n creates a new line in a string, thus splitting it into multiple lines. See the following example:

Output:

Hello
world

Here, the string is being split into two separate lines at the point where \n is placed.

Method 2: Using Triple Quotes

Python also allows you to create multiline strings using triple quotes. Any string placed between triple quotes will preserve the line breaks.

Output:

Hello
world

In the above example, the string is presented in two lines as it was written in the triple quotes.

Method 3: Using split() method

If you need to split a string into lines based on a specific character or string separator, you can use the split() method. This method splits a string into a list where each word is an item in the list.

Output:

Hello
world

The output is two separate lines as the split() method splits the original string at every instance of ‘-‘.

Here is the full code:

Hello
world
Hello
world
Hello
world

Conclusion

These techniques are very useful for handling and formatting strings in Python. Whether it’s generating structured output or processing large datasets, knowing how to split a string into multiple lines allows for greater flexibility and efficiency in your coding practices.