How to Split a String in Python?

In this python programming tutorial, I will show you how to split a string in python using indexes or delimiters.

How to Split a String in Python?
Photo by Tania Melnyczuk / Unsplash

There are multiple ways to split a string in Python. You could split a string with a delimiter (i.e., a character used as the cutting point) or use index locations to cut a string in specific ways. Here are some examples.

How to Split a String in Python Using a Delimiter?

my_long_string = "This,string,is,long" # The comma is the delimiter we will use and will not show up in the result of the action.
my_long_string_list = my_long_string.split(",")

# Result:
# ["This","string","is","long"]

The split() method must receive a delimiter to use. It could also be a space character " " that removes all spaces in your string.

Here's the official documentation to formally explain it.

How to Split a String in Python Using Indexes?

This method is less fun to use. You need to know the structure of the string before trying to cut it to pieces using indexes. Here's an example:

my_string = "msg: my name is Oren"

# You want to cut away the `msg: ` part and only keep the message itself.
my_cut_string = my_string[5:] # this means you're keeping the character in index 5 and onwards.
'my name is Oren'

# You can also just keep the msg part like so:
my_cut_string = my_string[:4]

This is how you play with indexes on strings and split them to your heart's desire.

In general, strings in Python could be treated as lists of characters. See the documentation for more potential actions on strings.

Remember! Indexes in Python begin with zero!


In this article, I showed you how to split strings in Python in two ways: by using delimiters or indexes.

I hope the examples make it clear! Let me know in the comments below whether there are any follow-up questions you want me to answer!

If you're interested in more tutorials like this one, check out the Python Programming page.

If you're looking for a free python course, check out my playlist on YouTube.