In Python you can split a string with the split() method. It breaks up a string (based on the given separator) and returns a list of strings.

To split a string, we use the method .split(). This method will return one or more new strings. All substrings are returned in a newly created list.

Note: Split with the method str.split(sep, maxsplit). The 2nd parameter is optional. If maxsplit is set, it returns no more than maxsplit elements.

Related course: Complete Python Programming Course & Exercises

Introduction

The split function breaks a string down into smaller chunks (a list of strings). Splitting a string is the opposite of concatenation (merges multiple strings into one string).

The split() method takes maximum of 2 parameters, of which one is optional. The syntax of the split() function is:

str.split([separator [, maxsplit]])

The first parameter seperator is the string to split on, this could be a space, a comma, a dash, a word etcetera.

The second parameter maxsplit is the maximum number of splits. By default there is no maximum and most programs don’t require a maximum number of splits.

String split example

We can split a string based on a character " ", this is named the seperator.

s = "To convert the result to"
parts = s.split(" ")
print(parts)
Result:

python split string

Any character (seperator) can be used. If you want to get sentences you could use:

s = "Python string example. We split it using the dot character."
parts = s.split(".")
print(parts)
This will result in:

['Python string example', ' We split it using the dot character', '']

It’s not limited to a space, you can seperate on a comma:

>>> s = "alice,allison,chicago,usa,accountant"
>>> s = s.split(",")
>>> s
['alice', 'allison', 'chicago', 'usa', 'accountant']
>>>

You can split on a dot (turning texts into individual sentences)

>>> s = "This is an example sentence. It has several words, and is in the English language. It's dummy data for Python."
>>> s = s.split(".")
>>> s
['This is an example sentence', ' It has several words, and is in the English language', " It's dummy data for Python", '']
>>>

The seperator can be a word instead of a single symbol or character

s = s.split("is")
s = s.split("python")

Note that we overwrite s, when calling the s.split() function. This is optional, if you want to keep the string you can store the result in a new variable.
Something like words = s.split()

If no separator is defined if you call the split() function, it will use a whitespace by default.

>>> s = "hello world how are you"
>>> print(s.split())
['hello', 'world', 'how', 'are', 'you']
>>>

Related course: Complete Python Programming Course & Exercises