The split()
method breaks down a string into a list of substrings using a chosen separator.
Example
text = 'Python is fun'
# split the text from space
print(text.split())
# Output: ['Python', 'is', 'fun']
split() Syntax
str.split(separator, maxsplit)
split() Parameters
The split()
method takes a maximum of 2 parameters:
- separator (optional) - Specifies the delimiter used to split the string. If not provided, whitespace is used as the default delimiter.
- maxsplit (optional) - Determines the maximum number of splits. If not provided, the default value is -1, which means there is no limit on the number of splits.
split() Return Value
The split()
method returns a list of strings.
Example: Python String split()
text= 'Split this string'
# splits using space
print(text.split())
grocery = 'Milk, Chicken, Bread'
# splits using ,
print(grocery.split(', '))
# splits using :
# doesn't split as grocery doesn't have :
print(grocery.split(':'))
Output
['Split', 'this', 'string'] ['Milk', 'Chicken', 'Bread'] ['Milk, Chicken, Bread']
Here,
text.split()
- splits the string into a list of substrings at each space character.grocery.split(', ')
- splits the string into a list of substrings at each comma and space character.grocery.split(':')
- since there are no colons in the string,split()
does not split the string.
Example: split() with maxsplit
We can use the maxsplit parameter to limit the number of splits that can be performed on a string.
grocery = 'Milk#Chicken#Bread#Butter'
# maxsplit: 1
print(grocery.split('#', 1))
# maxsplit: 2
print(grocery.split('#', 2))
# maxsplit: 5
print(grocery.split('#', 5))
# maxsplit: 0
print(grocery.split('#', 0))
Output
['Milk', 'Chicken#Bread#Butter'] ['Milk', 'Chicken', 'Bread#Butter'] ['Milk', 'Chicken', 'Bread', 'Butter'] ['Milk#Chicken#Bread#Butter']
Note: If maxsplit is specified, the list will have a maximum of maxsplit+1
items.
Also Read: