Introduction
The split()
method in Python is used to split a string into a list of substrings based on a specified delimiter. This method is commonly used in text processing tasks where parsing and breaking down strings is required. In this guide, we will explore the split()
method with practical examples and scenarios.
Basic Syntax
string.split([separator], [maxsplit])
Parameters:
- separator: (Optional) The delimiter to split the string. If not provided, whitespace is used by default.
- maxsplit: (Optional) The maximum number of splits to perform. Default is
-1
, meaning “no limit”.
Examples of split()
1. Splitting by Whitespace
# Example
text = "Python is fun"
words = text.split()
print(words)
# Output: ['Python', 'is', 'fun']
2. Splitting Using a Specific Delimiter
# Example
text = "apple,banana,cherry"
fruits = text.split(",")
print(fruits)
# Output: ['apple', 'banana', 'cherry']
3. Using maxsplit
Parameter
# Example
text = "one,two,three,four"
result = text.split(",", 2)
print(result)
# Output: ['one', 'two', 'three,four']
4. Splitting Multiline Strings
# Example
text = "line1\nline2\nline3"
lines = text.split("\n")
print(lines)
# Output: ['line1', 'line2', 'line3']
Advanced Use Cases
1. Splitting and Stripping Whitespaces
# Example
text = " hello world "
words = text.split()
print(words)
# Output: ['hello', 'world']
2. Splitting with Multiple Delimiters
To split a string using multiple delimiters, you can use the re.split()
method from the re
module.
import re
# Example
text = "apple;banana|cherry,grape"
fruits = re.split(r"[;|,]", text)
print(fruits)
# Output: ['apple', 'banana', 'cherry', 'grape']
Interview Questions
- Question 1: What is the default behavior of the
split()
method when no arguments are provided? - Question 2: How can you split a string into a maximum of three parts?
- Question 3: How would you split a string containing multiple delimiters like commas, semicolons, and pipes?
- Question 4: Write a Python function that splits a string by whitespace and removes empty strings from the result.
Conclusion
The split()
method is a fundamental tool for string manipulation in Python. Understanding its behavior and capabilities will help you efficiently handle text processing tasks. By mastering the various use cases and parameters, you can tackle any string-splitting challenge with ease.