How to Split a String in Python

Split a string into smaller parts is a very common task, to do so, we use the split() method in Python.

Let’s see some examples on how to do that.

Example 1: whitespaces as delimiters

In this example, we split the phrase by whitespaces creating a list named my_words with five items corresponding to each word in the phrase.

my_phrase = "let's go to the beach"
my_words = my_phrase.split(" ")

for word in my_words:
    print(word)
#output:
#let's
#go
#to
#the
#beach

print(my_words)
#output:
#["let's", 'go', 'to', 'the', 'beach']

Notice that, by default, the split() method uses any consecutive number of whitespaces as delimiters, we can change the code above to:

my_phrase = "let's go to the beach"
my_words = my_phrase.split()

for word in my_words:
    print(word)

#output:
#let's
#go
#to
#the
#beach

The output is the same since we only have 1 whitespace between each word.

Example 2: passing different arguments as delimiters

When working with data, it’s very common to read some CSV files to extract information from them.

As such, you might need to store some specific data from a certain column.

CSV files usually have fields separated by a semicolon ";" or a comma ",".

In this example, we are going to use the split() method passing as argument a specific delimiter, ";" in this case.

my_csv = "mary;32;australia;[email protected]"
my_data = my_csv.split(";")

for data in my_data:
    print(data)

#output:
#mary
#32
#australia
#[email protected]

print(my_data[3])
#output:
# [email protected]