Splitting Strings

How to Split a String With a Delimiter in Python

In Python, str.split() breaks a string into a list at each delimiter. Learn the separator, maxsplit and empty-piece rules, with examples and a C++ comparison.

On this page
  1. Split on a delimiter
  2. Empty pieces
  3. Limit the number of splits
  4. Split on white space
  5. Split on several delimiters
  6. Compared with C++

In Python, call split() on a string and pass the delimiter as the first argument. The result is a list of strings, one for each piece between delimiters. The original string does not change, because Python strings are immutable.

Split on a delimiter

fruit = "apple,banana,cherry"
parts = fruit.split(",")
print(parts)

The program prints:

['apple', 'banana', 'cherry']

Empty pieces

Two delimiters in a row create an empty string in the list, and so does a delimiter at the end:

print("a,,b".split(","))  # ['a', '', 'b']
print("a,b,".split(","))  # ['a', 'b', '']

Python keeps these empty strings. To remove them, filter the list with a comprehension: [part for part in text.split(",") if part].

Limit the number of splits

The optional maxsplit argument stops after a set number of splits. The rest of the text stays in the last piece:

print("name=Ada=Lovelace".split("=", 1))

This prints ['name', 'Ada=Lovelace'].

Split on white space

Called with no arguments, split() splits on runs of white space and drops empty pieces:

print("one  two\tthree".split())

This prints ['one', 'two', 'three'].

Split on several delimiters

str.split() takes one delimiter. For several, use the re module:

import re

print(re.split(r"[,;]", "red,green;blue"))

This prints ['red', 'green', 'blue']. An empty delimiter is not allowed: "abc".split("") raises a ValueError.

Compared with C++

C++ has no equivalent of str.split() in its standard library. The closest tool is std::getline with a std::stringstream, covered in How to Use split(). Two differences matter when you move between the languages. Python keeps a trailing empty piece, as "a,b,".split(",") shows, while std::getline drops it. And a bare split() in Python splits on white space, which in C++ you get with std::istringstream and >>.

Pass the delimiter you want, decide what to do with empty strings, and use maxsplit when only the first split matters.

The complete guide to splitting strings

How to Split a String by a Delimiter in C++
Read the guide

Keep exploring

Guides from other topics

All topics →

std::array in C++

A complete guide to std::array in C++: declaring, initializing, reading elements, looping, passing to functions, and how it compares to C-style arrays.

std::array 5 min read

Sets in C++: How std::set Works

Learn how C++ std::set stores unique values in sorted order, with examples of insert, find, erase, custom comparators, and how it differs from hash sets.

std::set 5 min read