split by newline python code example
Example 1: python split by newline
# Using str.splitlines() method, you can split a string by new lines
# Example 1
string = "Line 1\nLine 2\nLine 3\nLine4"
string = string.splitlines()
print(string)
# OUTPUT
['Line 1', 'Line 2', 'Line 3', 'Line4']
# Example 2
string = """Hello world.
My name is bob
I like dogs"""
string = string.splitlines()
print(string)
# OUTPUT
['Hello world.', 'My name is bob', '', 'I like dogs']
# 2.X Documentation: https://docs.python.org/2/library/stdtypes.html#str.splitlines
# 3.X Documentation: https://docs.python.org/3/library/stdtypes.html#str.splitlines
Example 2: python split lines
>>> text = """Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,
molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum
numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium
optio, eaque rerum! Provident similique accusantium nemo autem."""
# the str.splitlines() method is basically just str.split("\n").
>>> text.splitlines()
[
'Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,',
'molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum',
'numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium',
'optio, eaque rerum! Provident similique accusantium nemo autem.'
]
Example 3: how to split a string with newline in python
var = myString.splitlines()