The Python String split() method is a built-in function that splits the string based on the specified separator and returns a list of strings.
Also read How to Fix ValueError: If using all scalar values, you must pass an index
In this article, we will learn about the Python String split()
method with the help of examples.
split() Syntax
The Syntax of split()
method is:
str.split(separator, maxsplit)
split() Parameters
The split()
method takes two parameters, and both are optional.
- separator (optional) – Delimiter at which the string split should happen. If not provided, whitespace is taken as a separator, and the string will split at whitespaces.
-
maxsplit (optional) – An integer that tells us the maximum number of times the split should happen. If not provided, the default value is
-1
, which means there is no limit on the number of splits.
Example – If you would like to split the string on the occurrences of the first comma, you can set the maxsplit=1
The maxsplit=1
will split the string into 2 chunks—one with the string section before the first comma and another with the string section after the first comma.
split() Return Value
The split()
method returns the list of strings after breaking the given string by the specified character.
Example 1: How split() works in Python?
# splits by whitespace
text = "Python is fun"
print(text.split())
# splits the text after 'is' string
text = "Python is fun"
print(text.split('is'))
# cannot split as the character is not found
text = "Python is fun"
print(text.split('|'))
# splits by comma
fruits ="Apple, Grapes, Orange, Watermelon"
print(fruits.split(','))
Output
['Python', 'is', 'fun']
['Python ', ' fun']
['Python is fun']
['Apple', ' Grapes', ' Orange', ' Watermelon']
Example 2: How split() works when maxsplit is specified?
# splits by whitespace
text = "Python is really fun"
print(text.split(' ', 1))
# splits by comma
fruits = "Apple, Grapes, Orange, Watermelon"
print(fruits.split(',', 0))
# splits by comma
fruits = "Apple, Grapes, Orange, Watermelon"
print(fruits.split(',', 1))
# splits by comma
fruits = "Apple, Grapes, Orange, Watermelon"
print(fruits.split(',', 2))
# splits by comma
fruits = "Apple, Grapes, Orange, Watermelon"
print(fruits.split(',', 3))
Output
['Python', 'is really fun']
['Apple, Grapes, Orange, Watermelon']
['Apple', ' Grapes, Orange, Watermelon']
['Apple', ' Grapes', ' Orange, Watermelon']
['Apple', ' Grapes', ' Orange', ' Watermelon']
Top comments (0)