Python - How to split a String

By xngo on February 8, 2020

In Python, there is a neat little string function called split() that you can use to extract part of a string. It returns a list of splits in the string.

Extract date string

a_date="2020-01-27"
results = a_date.split('-')
print("year  = " + results[0])
print("month = " + results[1])
print("day   = " + results[2])

Output

year  = 2020
month = 01
day   = 27

Comma-separated string

animals = "monkey, dog, cat, bear, frog"
results = animals.split(',')
 
for animal in results:
    print(animal.strip()) # strip() used to trim spaces.

Output

monkey
dog
cat
bear
frog

Split up to N occurrences

You can use the maxsplit parameter to limit the number of splits. The example below will stop splitting after it found the 1st 2 splits.

animals = "monkey, dog, cat, bear, frog"
results = animals.split(', ', 2)
 
for animal in results:
    print(animal) # strip() used to trim spaces.

Output

monkey
dog
cat, bear, frog

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.