Python String | split()
Python String | split()
The Python split() method splits a string into a list of strings based on the specified separator.
Syntax: str.split(separator, maxsplit)
Parameters:
separator: This is the separator. The string will be split at this separator. If not provided, any whitespace will be used as a separator.
maxsplit: This is a number that tells us to split the string at most the number of times provided. If this number is not provided, it defaults to -1, meaning no limit.
Return Value: Returns a list of strings split by the specified delimiter.
Example 1: Example demonstrating how the split() function works.
text = 'geeks for geeks'
# Splits at space
print(text.split())
word = 'geeks, for, geeks'
# Splits at ','
print(word.split(','))
word = 'geeks:for:geeks'
# Splitting at ':'
print(word.split(':'))
word = 'CatBatSatFatOr'
# Splitting at t
print(word.split('t'))
Output:
['geeks', 'for', 'geeks']
['geeks', ' for', ' geeks']
['geeks', 'for', 'geeks']
['Ca', 'Ba', 'Sa', 'Fa', 'Or']
Example 2: Demonstrates how the split() function works when maxsplit is specified.
word = 'geeks, for, geeks, pawan'
# maxsplit: 0
print(word.split(', ', 0))
# maxsplit: 4
print(word.split(', ', 4))
# maxsplit: 1
print(word.split(', ', 1))
Output:
['geeks, for, geeks, pawan']
['geeks', 'for', 'geeks', 'pawan']
['geeks', 'for, geeks, pawan']