Use split() Function in Python with Example

The `split()` function in Python is used to split a string into a list of substrings based on a specified delimiter. By default, it splits the string at each whitespace.

Syntax

string.split(separator, maxsplit)

– separator (optional): The delimiter at which to split the string. If not provided, the string is split at any whitespace (space, newline, etc.).
– maxsplit (optional): The maximum number of splits to do. If not provided or set to `-1`, it splits at every occurrence of the separator.

Example 1: Splitting by Whitespace

text = "Python is an amazing language"
words = text.split()
print(words)

Output

['Python', 'is', 'an', 'amazing', 'language']

Example 2: Splitting by a Specific Delimiter

text = "apple,banana,cherry,dates"
fruits = text.split(',')
print(fruits)

Output

['apple', 'banana', 'cherry', 'dates']

Example 3: Using `maxsplit` Parameter

text = "one two three four five"
words = text.split(' ', 2)
print(words)

Output

['one', 'two', 'three four five']

Explanation

1. Example 1: The `split()` function splits the string `text` into a list of words at each whitespace because no delimiter was specified.
2. Example 2: The string is split into a list of fruits using a comma `,` as the delimiter.
3. Example 3: The string is split into a maximum of 2 parts. The first two words are split at spaces, and the remaining string is left as is.

These examples show how you can use the `split()` function to divide a string into a list of substrings based on various criteria.