Python Principles

How to split a string in Python

Strings are objects in Python. They have a method named split that lets you split the string.

Example of using split

For example, here is a string containing commas that we split:

>>> string = "red,blue,green"
>>> string.split(",")
['red', 'blue', 'green']

The split method

In general, the .split() method takes a string as its argument, and returns a list of strings.

Splitting by a pattern

You can split by a longer pattern:

>>> string = "this - also - works"
>>> string.split(" - ")
['this', 'also', 'works']

Split by whitespace

If you use split without giving any arguments, then the string will be split by any whitespace characters, such as spaces and tabs:

>>> string = "this is a\tstring"
>>> string.split()
['this', 'is', 'a', 'string']

Split at most n times

The second argument to split is the maximum number of times to split:

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

Split string starting at the end

You can use the rsplit method to split starting at the right instead of at the left:

>>> sentence = "hello world how are you"
>>> sentence.rsplit(" ", 2)
['hello world how', 'are', 'you']

The opposite of split

The join method is the opposite of split. For example:

>>> sentence = "hello world how are you"
>>> words = sentence.split(" ")
>>> reconstructed = " ".join(words)
>>> print(reconstructed)
hello world how are you