Python provides the string type which is a variable or value in order to store multiple characters. This can be also called the string used to store text data. As a popular type, the string type provides a lot of methods where in order to split strings 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 split 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 the below. We can see that every word is a list item.
['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. In the following example, we use the ;
and ,,
characters in order to split a string into a list.
sentence = "I;like;pythontect"
items = sentence.split(";")
print(items)
print("I,,like,,pythontect".split(",,"))
Specify Split Count (MaxSplit)
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 the below.
['I', 'like#pythontect'] ['I', 'like,,pythontect']
Split with Comma
Another popular string split character is the comma. We can split a string by using the comma as a delimiter.
sentence = "I,like,pythontect"
items = sentence.split(",")
print(items)
['I', 'like', 'pythontect']
Split Sentence Into Words
Another popular use case for the string splitting sentence into words. Whitespace is used to split a sentence into words where every word is an item in the returned list.
sentence = "I like pythontect"
items = sentence.split(" ")
print(items)
['I', 'like', 'pythontect']
Split with Hash Sign
We can use the hash sign
(#) in order to split a string. The string can be a sentence or another type of string.
s = "I#like#pythontect"
items = s.split("#")
print(items)