Convert a String to a List in Python Using split() – Examples
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
The split() method converts a string into a list by breaking it at a specified separator. When called without arguments, it splits on any whitespace and automatically removes leading, trailing, and repeated whitespace. This makes it useful for turning sentences into word lists.
You can also pass a delimiter, such as ",", ";", or "|", to split structured text like CSV-style data. The optional maxsplit parameter controls how many splits occur; for example, split(maxsplit=2) returns at most three list elements because the remainder stays together in the final item.
Input: a string and optional separator/maxsplit values. Output: a list of substrings. If the delimiter is not found, the original string appears as the only list element. Calling split() on an empty or whitespace-only string with no arguments returns an empty list.
Time complexity is generally O(n), where n is the length of the string, because Python scans the input to find separators and build the resulting list. Space complexity is O(n) in the worst case for the output list. Use split() whenever you need a simple, readable way to convert text into a Python list.