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:
Encode a String to UTF-8 in Java
Node.js vs Python for Backend Development
Python strftime()
Python Program to Append to a File
Most commonly used String methods in Java
Python Custom Exceptions
Python Program to Solve Quadratic Equation
Python Program to Check Whether a String is Palindrome or Not
Python Program to Return Multiple Values From a Function
Python format()
Python Program to Catch Multiple Exceptions in One Line
Python Program to Find the Factorial of a Number
Python String capitalize()
Python Set issuperset()
Python Program to Sort a Dictionary by Value
Java – Reader to String
String Set Queries
Python reversed()
Python pass statement
Python Dictionary popitem()
Python Program to Convert Two Lists Into a Dictionary
Python Program to Count the Number of Digits Present In a Number
Convert String to Byte Array and Reverse in Java
Python Program to Find Numbers Divisible by Another Number
Python Program to Extract Extension From the File Name
Converting a List to String in Java
Python frozenset()
Python Program to Add Two Numbers
Python Program to Make a Simple Calculator
Python File I/O Operation
Python Program to Print the Fibonacci sequence
Python Set isdisjoint()