Python provides the string type which is a variable or value in order to store multiple characters. This can be also called the string is used to store text data. As a popular type, the string type provides a lot of methods where in order to split string according to different cases the split() method is provided.
String split() Method Syntax
The split() method has the following syntax.
STRING.split(SEPARATOR,MAX_SPLIT)
- STRING is the string value or string variable.
- SEPARATOR is the single or multiple separator characters used to split given STRING. This parameter is optional.
- MAX_SPLIT is the number of the maximum slit count. This parameter is optional.
The split() method returns the splited items as a list.
Split with Whitespaces
By default, we can use the split() method without providing any parameter like separator or max split. This will split the given string into items in a list where the whitespace is the separator.
sentence = "I like pythontect"
items= sentence.split()
print(items)
print("I like pythontect".split())
The output will be like below.
['I', 'like', 'pythontect'] ['I', 'like', 'pythontect']
Split with Different Characters
By default, the split() method implicitly specifies the separator character as whitespace. But we can specify different characters as split or separator characters this can be a single character or multiple characters.
sentence = "I#like#pythontect"
items = sentence.split("#")
print(items)
print("I,,like,,pythontect".split(",,"))
Specify Split Count
By default, the given string variable or string value will be split with all items. But alternatively, we can specify the split count where only a given number of items will be split and returned as a list.
sentence = "I#like#pythontect"
items = sentence.split("#",1)
print(items)
print("I,,like,,pythontect".split(",,",1))
The output will be like below.
['I', 'like#pythontect'] ['I', 'like,,pythontect']