The split() method in Python is used to split a string into a list of substrings based on a specified delimiter. The syntax for the split() method is as follows:
string.split(separator, maxsplit)
where separator is the delimiter that separates the substrings in the string, and maxsplit is an optional parameter that specifies the maximum number of splits to perform.
Here’s an example of how to use the split() method:
string = "hello, world!"
words = string.split(", ")
print(words)
Output:
['hello', 'world!']
Example 1
The split() method is used without a separator to split the string “The quick brown fox jumps over the lazy dog” into a list of nine words based on whitespace characters. The resulting list is then assigned to the variable words.
string = "The quick brown fox jumps over the lazy dog"
words = string.split()
print(words)
Output:
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
Example 2
Splitting a string into a list of words, limited by a maximum number of splits.
string = "The quick brown fox jumps over the lazy dog"
words = string.split(maxsplit=3)
print(words)
Output:
['The', 'quick', 'brown', 'fox jumps over the lazy dog']
Example 3
Splitting a string into a list of words, ignoring leading/trailing whitespace.
string = " The quick brown fox jumps over the lazy dog "
words = string.strip().split()
print(words)
Output:
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']