Python - Split String into Lines


Python - Split string into lines

To split string into lines in Python, you can use string splitlines() method, or use string split() method with new line as separator.

In this tutorial, you will learn how to split a string into lines in Python using string splitlines() method, or string split() method, with examples.

Examples

1. Split string into lines using splitlines() method in Python

In this example, we are given a multiline string in x. We have to split this string into lines using splitlines() method.

Steps

  1. Given string is in x. This is a multiline string.
x = "Line 1\nLine 2\nLine 3"
  1. Call splitlines() method on string x.
x.splitlines()
  1. splitlines() method splits the string x into lines, and returns a list containing the lines of the string x. You may assign the returned value to a variable, and print the lines to standard output.
lines = x.splitlines()

Program

The complete Python program to split the string into lines using string splitlines() method.

Python Program

# Input string with multiple lines
x = "Line 1\nLine 2\nLine 3"

# Split the string into lines using splitlines()
lines = x.splitlines()

# Print each line
for line in lines:
    print(line)

Output

Line 1
Line 2
Line 3

2. Split string into lines using string split() method in Python

In this example, we are given a multiline string in x. We have to split this string into lines using Python string split() method.

Steps

  1. Given string is in x. This is a multiline string.
x = "Line 1\nLine 2\nLine 3"
  1. Call split() method on string x, and pass new line \n as argument for sep (separator) parameter.
x.split("\n")
  1. split() method splits the string x using given new line separator, and returns a list containing the parts. These parts are the lines because we have split the string using new line. You may assign the returned value to a variable, and print the lines to standard output.
lines = x.split()

Program

The complete Python program to split the string into lines using string split() method.

Python Program

# Input string with multiple lines
x = "Line 1\nLine 2\nLine 3"

# Split the string into lines using split()
lines = x.split("\n")

# Print each line
for line in lines:
    print(line)

Output

Line 1
Line 2
Line 3

Summary

In this tutorial, we learned how to split a string into lines using string splitlines() method or string split() method.