split() Function
The split() Function is used to split a String into a list.
x = "Hello Beautiful World" y = x.split() print(y)
So, in the above code, we have a String 'Hello Beautiful World' initialised to a variable 'x'.
Then we have used the 'split( )' function on the variable 'x'.
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'.
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 '@'.
Now, if you want to form a list with 'Hello', 'Beautiful' and 'World'. You can use 'split()' function providing the separator '@' as argument.
x = "Hello@Beautiful@World" y = x.split("@") print(y)
So, in the above code, we have a String 'Hello@Beautiful@World' initialised to a variable 'x'.
Then we have used the 'split()' function with the separator '@' as argument on the variable 'x'.
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'.
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'
We can achieve the above using a second parameter that specifies the number of list elements.
x = "Hello@Beautiful@World" y = x.split("@", 1) print(y)
So, in the above code, we have a String 'Hello@Beautiful@World' initialised to a variable 'x'.
Then we have used the 'split( )' function with the separator '@' and '1' as arguments on the variable 'x'.
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'.