Table of Contents
In this tutorial, we will learn about the Python String split() method with the help of examples.
The split() method breaks up a string at the specified separator and returns a list of strings.
Example
text = 'Python is a fun programming language'
# split the text from space
print(text.split(' '))
# Output: ['Python', 'is', 'a', 'fun', 'programming', 'language']
1. Syntax of String split()
The syntax of split() is:
str.split(separator, maxsplit)
2. split() Parameters
The split() method takes a maximum of 2 parameters:
- separator (optional)- Delimiter at which splits occur. If not provided, the string is splitted at whitespaces.
- maxsplit (optional) – Maximum number of splits. If not provided, there is no limit on the number of splits.
3. split() Return Value
The split() method returns a list of strings.
4. Example 1: How split() works in Python?
text= 'Love thy neighbor'
# splits at space
print(text.split())
grocery = 'Milk, Chicken, Bread'
# splits at ','
print(grocery.split(', '))
# Splits at ':'
print(grocery.split(':'))
Output
['Love', 'thy', 'neighbor'] ['Milk', 'Chicken', 'Bread'] ['Milk, Chicken, Bread']
5. Example 2: How split() works when maxsplit is specified?
grocery = 'Milk, Chicken, Bread, Butter'
# maxsplit: 2
print(grocery.split(', ', 2))
# maxsplit: 1
print(grocery.split(', ', 1))
# maxsplit: 5
print(grocery.split(', ', 5))
# maxsplit: 0
print(grocery.split(', ', 0))
Output
['Milk', 'Chicken', 'Bread, Butter'] ['Milk', 'Chicken, Bread, Butter'] ['Milk', 'Chicken', 'Bread', 'Butter'] ['Milk, Chicken, Bread, Butter']
If maxsplit is specified, the list will have a maximum of maxsplit+1 items.
Related posts:
Python Program to Find HCF or GCD
Python String title()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python ord()
Python round()
Python String startswith()
Python String format()
Python Program to Iterate Through Two Lists in Parallel
Why String is Immutable in Java?
Python Set difference()
Python bool()
Python Exception Handling Using try, except and finally statement
Python Program to Check If Two Strings are Anagram
Most commonly used String methods in Java
Python Inheritance
Count Occurrences of a Char in a String
Python list()
Python vars()
Python int()
Python Program to Remove Punctuations From a String
Python Program to Access Index of a List Using for Loop
Python type()
Java Program to Permute All Letters of an Input String
Introduction to Machine Learning with Python - Andreas C.Muller & Sarah Guido
Java – Generate Random String
Python print()
Python Dictionary popitem()
Python Modules
Python Decorators
Python min()
Python String maketrans()
Python Set pop()