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

Improve your Python skills fast

The fastest way to learn programming is with lots of practice. Learn a programming concept, then write code to test your understanding and make it stick. Try our online interactive Python course today—it's free!

Learn more about the course

Want to get better at Python quickly? Try our interactive lessons today! Memberships are 100% FREE this week only!