API Navigator Logo

How to Split a String in Python

Author: Newtum

This example covers the use of the `str.split()` method to break a string into a list of substrings based on a specified delimiter.

Basic Splitting

By default, `split()` divides a string at each whitespace character (like space, tab, or newline) and returns a list of the resulting words.

sentence = "This is a sample sentence."
words = sentence.split()
print(words)

Splitting by a Specific Delimiter

You can provide a delimiter as an argument to `split()` to divide the string at every occurrence of that delimiter.

csv_data = "apple,banana,cherry,date"
fruits = csv_data.split(',')
print(fruits)

path = "/usr/local/bin/python"
path_components = path.split('/')
print(path_components)

Limiting the Number of Splits

The `maxsplit` parameter lets you control the maximum number of splits that will occur. The rest of the string is returned as the last element of the list.

line = "key1:value1:key2:value2"

# Split only on the first colon
result1 = line.split(':', 1)
print(result1)

# Split on the first two colons
result2 = line.split(':', 2)
print(result2)