English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The split() method splits a string at the specified separator and returns a list of strings.
The syntax of split() is:
str.split([separator, [maxsplit]])
The split() method can use at most2a parameter:
separator(Optional)-is the separator. The string is split at the specified separator (separator).
If the separator is not specified, any space (space, newline, etc.) string is a separator.
maxsplit(Optional)- maxsplit defines the maximum number of splits.
The default value is maxsplit-1means that the split number is unlimited.
split() splits the string at the separator and returns a list of strings.
text = 'Love thy neighbor' # Split at space print(text.split()) grocery = 'Milk, Chicken, Bread' # Split at ',' print(grocery.split(', ')) # Split at ':' print(grocery.split(':'))
When running the program, the output is:
['Love', 'thy', 'neighbor'] ['Milk', 'Chicken', 'Bread'] ['Milk, Chicken, Bread']
grocery = 'Milk, Chicken, Bread, Butter' # maxsplit: 2 print(grocery.split(', ')) 2)) # maxsplit: 1 print(grocery.split(', ')) 1)) # maxsplit: 5 print(grocery.split(', ')) 5)) # maxsplit: 0 print(grocery.split(', ', 0))
When running the program, the output is:
['Milk', 'Chicken, Bread, Butter'] ['Milk', 'Chicken, Bread, Butter'] ['Milk', 'Chicken', 'Bread', 'Butter'] ['Milk, Chicken, Bread, Butter']
If maxsplit is specified, the list will contain at most maxsplit+1project.