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




split( ) FUNCTION


split() Function


The split() Function is used to split a String into a list.


Example :


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


Output :



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

So, in the above code, we have a String 'Hello Beautiful World' initialised to a variable 'x'.


java_Collections

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


y = x.split( )

So, the 'split()' function converts the String, 'Hello Beautiful World' to a list, separated by a space (i.e. ' ').


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 a space (i.e. ' ').


So, a list is formed with 'Hello', 'Beautiful' and 'World'.


But what if the Strings are separated by '@' or any other symbol.


Say, the below String is separated by '@'.


"Hello@Beautiful@World"

Now, if you want to form a list with 'Hello', 'Beautiful' and 'World'. You can use 'split()' function providing the separator '@' as argument.


'split( )' Function using separator as an argument


Example :


x = "Hello@Beautiful@World"
y = x.split("@")
print(y)


Output :



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

So, in the above code, we have a String 'Hello@Beautiful@World' initialised to a variable 'x'.


java_Collections

Then we have used the 'split()' function with the separator '@' as argument on the variable 'x'.


y = x.split("@")

So, the 'split( )' function converts the String, 'Hello@Beautiful@World' to a list, separated by the separator (i.e. '@').


And initialises the list to the variable 'y'.


java_Collections

In the above example, we have three items in the list. But what if, you want only two items in the list.


i.e. For the same String, 'Hello@Beautiful@World', we just want two items in the list, 'Hello' and 'Beautiful@World'


java_Collections

We can achieve the above using a second parameter that specifies the number of list elements.


'split( )' Function using separator and number of list elements as arguments


Example :


x = "Hello@Beautiful@World"
y = x.split("@", 1)
print(y)


Output :



  ['Hello', 'Beautiful@World']

So, in the above code, we have a String 'Hello@Beautiful@World' initialised to a variable 'x'.


java_Collections

Then we have used the 'split( )' function with the separator '@' and '1' as arguments on the variable 'x'.


y = x.split("@", 1)

So, the 'split( )' function converts the String, 'Hello@Beautiful@World' to a list, separated by the separator (i.e. '@').


And initialises the list to the variable 'y'.


java_Collections

Note : If you want a list of size '2'. Just specify the size '1' and it would create a list of size '2'.