The split() method in Python is used to split a string into a list of substrings based on a specified delimiter (separator). If no separator is provided, it splits on whitespace by default.
Syntax
python
string.split(separator, maxsplit)
– separator (optional): The delimiter on which the string will be split. Default is any whitespace.
– maxsplit (optional): Specifies the maximum number of splits. The default is -1, which means no limit.
Examples
- Split on Whitespace (Default)
python
text = “Python is fun”
words = text.split()
print(words) # Output: [‘Python’, ‘is’, ‘fun’] -
Split Using a Specific Separator
python
text = “apple,banana,cherry”
fruits = text.split(“,”)
print(fruits) # Output: [‘apple’, ‘banana’, ‘cherry’] -
Using maxsplit
python
text = “apple,banana,cherry,grape”
fruits = text.split(“,”, maxsplit=2)
print(fruits) # Output: [‘apple’, ‘banana’, ‘cherry,grape’] -
Split Using Multiple Whitespace
python
text = ” Python is fun ”
words = text.split()
print(words) # Output: [‘Python’, ‘is’, ‘fun’] -
Split Using Special Characters
python
text = “hello#world#python”
parts = text.split(“#”)
print(parts) # Output: [‘hello’, ‘world’, ‘python’]
Points to Remember
1. If no separator is specified, split() treats consecutive whitespace as a single separator.
2. If the string does not contain the separator, the entire string is returned as a single element in the list.
3. split() does not modify the original string.
Example:
python
text = “apple,banana”
parts = text.split(“;”)
print(parts) # Output: [‘apple,banana’]
The split() method is useful for parsing strings and processing text data efficiently!