Python str.split() function
In Python, the str.split()
method is used to divide a string into a list of substrings based on a specified separator. By default, it splits the string at whitespace characters. This method is very useful for processing and analyzing text data.
Syntax
- sep (optional): The delimiter (separator) string that determines where the splits should occur. If not specified, the method splits at any whitespace and discards empty strings from the result.
- maxsplit (optional): The maximum number of splits to perform. If specified, the resulting list will have at most
maxsplit + 1
elements. The default value of-1
means "all occurrences."
Example Usage
- Basic usage without a separator:
- Using a specific separator:
- Using maxsplit:
- Handling multiple separators:
- Using whitespace as a separator:
Summary
- Use
str.split()
to break a string into a list of substrings. - You can specify a delimiter to control how the string is split and limit the number of splits with
maxsplit
. - The method is versatile for different types of string processing tasks, particularly in data cleaning and preparation.