split() method is used to divide a string into multiple parts based on a specified separator. It returns the resulting parts as a list of strings.
s = "one,two,three"
words = s.split(',')
print(words)
Output
['one', 'two', 'three']
Explanation: s.split(',') splits the string s at every comma and returns a list of the parts ['one', 'two', 'three'].
Syntax
str.split(separator, maxsplit)
Parameters:
- separator (optional): Specifies the delimiter used to split the string. If not provided, whitespace characters (spaces, tabs and newlines) are used by default.
- maxsplit (optional): Specifies the maximum number of splits to perform. The default value is -1, which means the string is split at all occurrences of the separator.
Return Value: Returns a list of strings containing the parts obtained after splitting the original string.
Splitting Strings with Multiple Spaces
When no separator is specified, consecutive whitespace characters are treated as a single separator.
text = "Hello world"
print(text.split())
Output
['Hello', 'world']
Explanation: string contains multiple spaces between "Hello" and "world" and split() automatically treats consecutive spaces as a single separator.
Splitting with Different Separators
By default, split() uses whitespace as the separator. However, you can provide any character or string as a delimiter to split the text based on your specific requirements.
text = "geeks for geeks"
print(text.split())
text = "geeks,for,geeks"
print(text.split(","))
text = "geeks:for:geeks"
print(text.split(":"))
text = "CatBatSatFatOr"
print(text.split("t"))
Output
['geeks', 'for', 'geeks'] ['geeks', 'for', 'geeks'] ['geeks', 'for', 'geeks'] ['Ca', 'Ba', 'Sa', 'Fa', 'Or']
Explanation:
- split() without arguments splits the string at whitespace characters.
- split(",") splits the string wherever a comma appears.
- split(":") splits the string at each colon.
- split("t") splits the string at every occurrence of the character t.
Using maxsplit
The maxsplit parameter limits the number of splits performed on a string. Once the specified number of splits is reached, the remaining part of the string is returned as a single element.
text = "apple, banana, mango, orange"
print(text.split(", ", 0))
print(text.split(", ", 4))
print(text.split(", ", 1))
Output
['apple, banana, mango, orange'] ['apple', 'banana', 'mango', 'orange'] ['apple', 'banana, mango, orange']
Explanation:
- maxsplit=0 performs no splitting and returns the original string as a single list element.
- maxsplit=4 allows splitting at all available occurrences of ", ".
- maxsplit=1 performs only one split and keeps the remaining text together.
Parsing a Sentence into Words
Most common uses of split() is breaking a sentence into individual words. This is useful in text processing, word counting and natural language processing tasks.
text = "Welcome to Python programming."
words = text.split()
print(words)
Output
['Welcome', 'to', 'Python', 'programming.']