In python, the string split() method is useful to split the string into a list that contains substrings, and those are separated by the specified separator.
Following is the pictorial representation of string split() method functionality in python.
If you observe the above diagram, we are splitting the string "Suresh-Rohini-Trishika
" with "-
" separator using the python split method. Once splitting is done, the split method will return a list of words in the string.
Following is the syntax of defining a string split method in python.
If you observe the above syntax, the split()
method is accepting two parameters (separator, maxsplit)
and those are optional.
whitespace
as a separator to split the strings.maxsplit
value is considered as -1
that means no limit on the number of splits.Following is the example of splitting the given strings with required delimiters using the split()
method in python.
If you observe the above example, we are splitting the strings with different delimiters using the split()
method without specifying the maxsplit
parameter.
When you execute the above python program, you will get the result as shown below.
In the above example, we didn’t mention any limit (maxsplit
) on the number of splits so the split()
method by default considered maxsplit
as -1
and returned the list of all strings.
In case if you want to limit the number of strings split, you need to mention maxsplit
parameter value in the split()
method. If maxsplit
specified, the split()
method will return a maximum of maxsplit + 1
items.
Following is the example of splitting the string into a list by using the split() method and limit the number of strings split with maxsplit parameter value.
If you observe the above example, we are limiting the string split by specifying the maxsplit
parameter value in the split()
method.
When you execute the above python program, you will get the result as shown below.
This is how you can use the string split() method in python to split the string into a list based on your requirements.