Python String split() Method

The split() method is used to break up a string into a list of substrings based on a specified separator.

Syntax

string.split(separator, maxsplit)

Parameters

separator (Optional): The delimiter at which the string is split. If this parameter is not provided, the string is split at any whitespace (like spaces, tabs, or newlines).

maxsplit (Optional): Maximum number of splits to perform. The default is -1, which means “all possible splits“.

Return Value

Returns a list of substrings.

Examples

Default Behavior (No Separator)

If you don’t provide a separator, the split() method defaults to splitting the string at any whitespace character (like spaces, tabs, or newlines).

text = "Python is awesome"
words = text.split()
print(words) # Output: ['Python', 'is', 'awesome']

Using a Custom Separator

You can split a string using a specific character or sequence of characters, such as a comma, hyphen, or any custom delimiter.

text = "apple, banana, mango"
words = text.split(', ')
print(words) # Output: ['apple', 'banana', 'mango']

Splitting on Multiple Characters

text = "apple#&banana#&mango"
words = text.split('#&')
print(words) # Output: ['apple', 'banana', 'mango']

Limiting the Number of Splits

The maxlimit parameter limits the number of times the string is split.

text = "apple, banana, mango"
words = text.split(', ', 1)
print(words) # Output: ['apple', 'banana, mango']

Note: If you need to split the string from the right side, you can use the rsplit() method.