Python 3 – String split() Method
The split() method in Python is an incredibly useful method that allows you to split a string into a list. This means that you can take a single string with multiple words, and create a list of each individual word. The split() method is easy to use and has a lot of different applications.
Syntax
string.split(separator, maxsplit)
- separator (optional): This is the character that will be used to separate the string. If this parameter is left blank, the separator will be a whitespace.
- maxsplit (optional): This parameter is used to specify how many splits to make. By default (when the parameter is not provided), the method will split the string into as many parts as possible.
Example
Let’s take a look at an example of how you can use the split() method:
sentence = "The quick brown fox jumps over the lazy dog"
words = sentence.split()
print(words)
Output:
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
In this example, we take a string “The quick brown fox jumps over the lazy dog” and use the split() method to create a list of each individual word in the sentence. We then print this list, which returns:
['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
Splitting with a Specific Separator
Besides splitting words with whitespace, you can also split a string on any other character. For example, if you want to split a sentence using a comma as a separator, you would write:
sentence = "apples, pears, and bananas"
words = sentence.split(",")
print(words)
Output:
['apples', ' pears', ' and bananas']
In this example, we use a comma (“,”) as our separator, and the split() method creates a list of three elements: ‘apples’, ‘pears’, and ‘bananas’.
If you want to split a string using a hyphen as a separator, you can write:
sentence = "watermelon-pineapple-mango"
words = sentence.split("-")
print(words)
Output:
['watermelon', 'pineapple', 'mango']
Limiting the Number of Splits
You can also limit the number of splits that the split() method will make. This is done by adding a second parameter, which specifies the maximum number of splits to make. Let’s look at an example:
sentence = "The quick brown fox jumps over the lazy dog"
words = sentence.split(" ", 3)
print(words)
Output:
['The', 'quick', 'brown', 'fox jumps over the lazy dog']
In this example, we use whitespace as our separator, and limit the number of splits to 3. This means that only the first 3 words in the sentence will be split into a separate list element.
Conclusion
In conclusion, the split() method in Python is an incredibly useful tool for splitting a string into a list. By default, it splits on whitespace, but you can specify any separator you want. You can also limit the number of splits that are made. The split() method is easy to use and can save you a lot of time if you need to work with strings in your Python code.