Python string split() function is used to split a string into the list of strings based on a delimiter.
sep
argument is used as the delimiter. If the string contains consecutive delimiters, then an empty string is returned. Delimiter argument can be of multiple characters too.
If the delimiter is not provided or None
, then whitespaces are considered as the delimiter. In this case, no empty string will be returned in case there are leading or trailing white spaces. Also, multiple whitespaces will be considered as a single delimiter.
If maxsplit is provided, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits and all possible splits are returned in the list.
Let’s look at a simple example where a string will be split into a list based on the specified delimiter.
Output:
Output: ['Python', 'is Nice']
Notice that returned list has only 2 items, the string was split only once.
Output: ['Java', 'Python', 'iOS', 'Android']
The leading and trailing whitespaces are ignored in the returned list. Also, consecutive whitespaces are also considered as a single delimiter.
Output:
Output: ['Hi', 'Hello', 'Adios']
We can use split() function directly from str class too.
Output:
Notice that empty string is returned when the first character matches the separator.
Finally, let’s look at a real-life example where the user will enter the CSV data and we will split it into the list of strings.
Output:
That’s all for python string split() function examples. It’s a very useful function to split a string into the list based on some delimiter.
Python string rsplit() function is very similar to split() function. The only difference is that the splits are done starting at the end of the string and working to the front.
Let’s look at some of the rsplit() function examples.
Output:
Notice that the difference is visible when maxsplit argument is provided. Otherwise, the split() and rsplit() function output is same.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
This comment has been deleted