Definition
The split() method splits a string into a list. Default separator is any whitespace, but it can also be specified. Note that when maxsplit is specified, the list will contain the specified number of elements plus one.
Syntax
string.split(separator, maxsplit)
Parameters
Parameter | Description |
---|---|
separator | Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator |
maxsplit | Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences" |
Examples:
myStr = "Hello! Welcome to the Python tutorials."
result = myStr.split()
print(result)
# using a specific separator
myStr = "Hello! Welcome! to! the! Python! tutorials!"
result = myStr.split("! ")
print(result)
# using the maxsplit parameter
myStr = "Hello! Welcome! to! the! Python! tutorials!"
result = myStr.split("! ", 2)
print(result)