Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




splitlines( ) FUNCTION


splitlines( ) Function


The splitlines( ) Function is used to split a String into a list based on a newline.


Example :


x = """Hello
Beautiful
World"""
y = x.splitlines()
print(y)


Output :



  ['Hello', 'Beautiful', 'World']

So, in the above code, we have a String,


Hello
Beautiful
World

Separated by multiple lines. And as we know, String with multiple lines is represented by three double quotes(i.e. """ """)


x = """Hello
Beautiful
World"""

Initialised to a variable 'x'.


java_Collections

Then we have used the 'splitlines( )' function on the variable 'x'.


y = x.splitlines( )

And, the 'splitlines( )' function converts the String to a list, separated by new line.


And initialises the list to the variable 'y'.


java_Collections

So, if you see the above String,


Hello
Beautiful
World.

'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'.


Example :


x = "Hello\nBeautiful\nWorld"
y = x.splitlines()
print(y)    


Output :



  ['Hello', 'Beautiful', 'World']

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.


x = "Hello\nBeautiful\nWorld"

And, initialised to a variable 'x'.


java_Collections

Then we have used the 'splitlines( )' function on the variable 'x'.


y = x.splitlines( )

And, the 'splitlines( )' function converts the String to a list, separated by new line.


And initialises the list to the variable 'y'.


java_Collections

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.


Example :


x = "Hello\nBeautiful\nWorld"
y = x.splitlines(True)
print(y)  


Output :



  ['Hello\n', 'Beautiful\n', 'World']

And we have got the above output.


Just remember, to make the first letter of 'True' in Upper case i.e. 'T'.


y = x.splitlines(True)