A string in Python is a sequence of characters enclosed within single or double-quotes. In Python, the
print() function is used to display a string on the standard output.
If you often program in Python you may find sometimes you need to break or split a string based on whitespace, comma, or any other separator. For this purpose python split() method is used.
This article describes how to split a string in Python.
Python split() method
The split() method in Python is used to break a string into a list of multiple strings. The syntax of this method is given below.
str is the string to split
separator is a delimiter. String splits at the specified separator. If it is not provided whitespace will be considered as the separator.
maxsplit defines the maximum number of splits by default it is -1 which means there is no limit on the number of splits.
Splitting a string in Python
The given Python examples show you how to split a string.
In the given example whitespace is used as the separator that means the given string will split from every space that occurs in the string.
string='This is Python programming' print(string.split())
Save this file with ex1.py and execute it. This will display the output you can see this in the image below.
The consecutive whitespaces will cause to create empty strings.
In this second example, we use a comma as a separator now the string fruits will split from each comma that occurred in the string.
fruits = 'apple, banana, grapes, orange' print(fruits.split(','))
Save this file with ex2.py and execute it. You can see the output in the image below.
When we pass the value of max split it will limit the maximum number of splits you can see this in the given modified code.
fruits = 'apple, banana, grapes, orange' # pass maxsplit as 1 print(fruits.split(',')) # pass maxsplit as 2 print(fruits.split(','))
You can see the output of this code in the image below.
In our third example, we will use a dot or full stop as a separator. The string defined here is a multiline string in which each sentence is separated by a full stop. Using a full stop or dot as a separator will break all the sentences of this string.
string ='''Nautilus is a file manager for gnome desktops. It allows one to browse directories and open an application associated with them. It is also responsible for icon handling in gnome desktops.''' print(string.split('.'))
You can see the output of this code in the given image.
In this article, you learned how to split a string in Python. Now if you have a query or feedback write it in the comments below.