splitlines( ) Function
The splitlines( ) Function is used to split a String into a list based on a newline.
x = """Hello Beautiful World""" y = x.splitlines() print(y)
So, in the above code, we have a String,
Separated by multiple lines. And as we know, String with multiple lines is represented by three double quotes(i.e. """ """)
Initialised to a variable 'x'.
Then we have used the 'splitlines( )' function on the variable 'x'.
And, the 'splitlines( )' function converts the String to a list, separated by new line.
And initialises the list to the variable 'y'.
So, if you see the above String,
'Hello', 'Beautiful' and 'World' are separated by new line.
So, a list is formed with 'Hello', 'Beautiful' and 'World'.
Let us rewrite the above example using the escape character for newline i.e. '\n'.
x = "Hello\nBeautiful\nWorld" y = x.splitlines() print(y)
So, in the above code, we have a String, 'Hello\nBeautiful\nWorld', separated by newline.
And this time, we have used the escape character '\n' as newline.
And, initialised to a variable 'x'.
Then we have used the 'splitlines( )' function on the variable 'x'.
And, the 'splitlines( )' function converts the String to a list, separated by new line.
And initialises the list to the variable 'y'.
Now, let us say, you want the the escape character newline '\n' to be a part of the list.
Well ! You can have that by providing the value 'true' in the parameter of the 'splitlines( )' function.
x = "Hello\nBeautiful\nWorld" y = x.splitlines(True) print(y)
And we have got the above output.
Just remember, to make the first letter of 'True' in Upper case i.e. 'T'.