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:
1 2 |
string = "Hello\nworld" print(string) |
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.
1 2 3 |
string = """Hello world""" print(string) |
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.
1 2 3 4 |
string = "Hello-world" split_string = string.split('-') for s in split_string: print(s) |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Method 1 string = "Hello\nworld" print(string) # Method 2 string = """Hello world""" print(string) # Method 3 string = "Hello-world" split_string = string.split('-') for s in split_string: print(s) |
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.