One of the common operations when working with strings is to split a string to an array of substrings using a given delimiter.
In this article, we will talk about how to split string in Python.
.split() Method
In Python, strings are represented as immutable str
objects. The str
class comes with a number of string methods that allow you to manipulate the string.
The .split()
method returns a list of substrings separated by a delimiter. It takes the following syntax:
str.split(delim=None, maxsplit=-1)
The delimiter can be a character or sequence of characters, not a regular expression.
In the example below we’re splitting the string s
using the comma ,
as a delimiter:
s = 'Sansa,Tyrion,Jon'
s.split(',')
The result is a list of strings:
['Sansa', 'Tyrion', 'Jon']
String literals are usually enclosed by single quotes, although double quotes can be used too.
A sequence of characters can also be used as a delimiter:
s = 'Sansa::Tyrion::Jon'
s.split('::')
['Sansa', 'Tyrion', 'Jon']
When maxsplit
is given, it will limit the number of splits. If not specified or -1
, there is no limit on the number of splits.
s = 'Sansa;Tyrion;Jon'
s.split(';', 1)
The result list will have maximum maxsplit 1
elements:
['Sansa', 'Tyrion;Jon']
If the delim
is not specified or it is Null
, the string will be split using whitespace as a delimiter. All consecutive whitespace are considered as a single separator. Also, if the string contains trailing and leading whitespaces the result, will have no empty strings.
To better illustrate this, let’s take a look at the following example:
' Daenerys Hodor Arya Jaime Bran '.split()
['Daenerys', 'Hodor', 'Arya', 'Jaime', 'Bran']
' Daenerys Hodor Arya Jaime Bran '.split(' ')
['', 'Daenerys', '', 'Hodor', 'Arya', '', '', 'Jaime', 'Bran', '']
When no delimiter is used, the returning list contains no empty strings. If the delimiter is set to an empty space ' '
the leading, trailing, and consecutive whitespace will cause the result to contain empty strings.
Conclusion
Splitting strings is one of the most basic operations. After reading this tutorial, you should have a good understanding of how to split strings in Python.
If you have any questions or feedback, feel free to leave a comment.