The String split() method returns a new list containing the substrings based on a specified separator.
By default, the separator is whitespace, but you can specify a different separator as per your requirements.
Syntax
string.split(separator, maxsplit)
Parameters
- separator(optional): This is a delimiter argument. It is the separator on which the string splits occur. If not provided or None, the string is split at whitespaces.
- maxsplit(optional): It is a number that tells us to split the string into a maximum of the provided number of times. The default value is -1, meaning all occurrences.
Example 1: Splitting by whitespace(default)
text = "Welcome to AppDividend"
print("Before splitting: ",text)
words = text.split()
print("After splitting: ",words)
print(type(words))
Output
Before splitting: Welcome to AppDividend
After splitting: ['Welcome', 'to', 'AppDividend']
<class 'list'>
Example 2: Splitting by a specific character
text = "Welcome@to@AppDividend"
print("Before splitting: ",text)
words = text.split('@')
print("After splitting: ",words)
Output
Before splitting: Welcome@to@AppDividend
After splitting: ['Welcome', 'to', 'AppDividend']
Example 3: Using maxsplit
text = "Welcome@to@AppDividend"
# Printing the original text before splitting
print("Before splitting: ", text)
# Using the split with '@' as the separator and a maxsplit of 1
words = text.split('@', 1)
# Printing the result after the first split
print("After splitting: ", words)
# Using the split again with '@' as the separator and a maxsplit of 2
words2 = text.split('@', 2)
# Printing the result after the second split
print("After splitting: ", words2)
Output
Before splitting: Welcome@to@AppDividend
After splitting: ['Welcome', 'to@AppDividend']
After splitting: ['Welcome', 'to', 'AppDividend']