
Python String Split() Function: Complete Guide with Examples
Python String Split() Function: Python’s split() function is a powerful tool for string manipulation. It helps break a string into multiple substrings based on a specified delimiter or character. In this guide, we’ll explore the syntax, use cases, and examples to help you understand the split() function in detail.
What is the split() Function in Python?
Python String Split() Function: The split() function divides a string into smaller substrings. It returns these substrings as elements of a list. If no delimiter is specified, whitespace is used by default.
Syntax of split() Function
python
string.split(separator, max)
Python String Split() Function Parameters:
- separator (Optional): The delimiter used to split the string (e.g., comma, space, etc.).
- max (Optional): The maximum number of splits to perform.
Return Value:
The function returns a list of substrings.
Why Use the split() Function in Python?
- Efficiently splits long strings or sentences into smaller parts.
- Handles both default whitespace splitting and custom delimiters.
- Provides flexibility with the maxsplit parameter for controlled splits.
Examples of split() Function Usage
1. Splitting a String Using a Space (Default Behavior)
python
text = “Hello World Software Moji Moji”
print(text.split())
Output:
css
[‘Hello’, ‘World’, ‘Software’, ‘Moji’, ‘Moji’]
2. Splitting a String Using a Comma Delimiter
python
text = “Hello,World,Software,Moji,Moji”
print(text.split(“,”))
Output:
css
[‘Hello’, ‘World’, ‘Software’, ‘Moji’, ‘Moji’]
3. Splitting a String Using a Specific Character as a Delimiter
python
text = “Hello World Software Moji Moji”
print(text.split(“l”))
Output:
css
[‘He’, ”, ‘o Wor’, ‘d Software Moji Moji’]
4. Splitting a String into a List
python
text = “Hello World Software Moji Moji”
list_1 = text.split()
for word in list_1:
print(word)
Output:
nginx
Hello
World
Software
Moji
Moji
5. Splitting a String with maxsplit Parameter
python
text = “Hello,World,Software,Moji,Moji”
print(text.split(“,”, 2))
Output:
css
[‘Hello’, ‘World’, ‘Software,Moji,Moji’]
6. Splitting a String Using a Substring
python
text = “Hello World Software Moji Moji”
split_1 = text.split(“Software Moji”, 1)
print(split_1)
Output:
css
[‘Hello World ‘, ‘ Moji’]
Importance of split() Function in Python
- Useful in text data processing and text mining projects.
- Helps manage and manipulate strings effectively.
- Ideal for handling CSV files, data extraction, and data cleaning tasks.