Python String split()

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.

Syntax

The Syntax of split() method is:

str.split(separator, maxsplit)

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. 

Return Value

The split() method returns the list of strings after breaking the given string by the specified character.

Example 1: How to split() string 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: String split() using both separator and maxsplit argument

# 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']
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Python Slice()

Python slice()

Table of Contents Hide slice() Syntax slice() Parametersslice() Return ValueExample 1: Python slice string Get substring using slice objectExample 2: Get substring using negative indexExample 3: Python slice list or Python slice arrayExample 4: Python…
View Post