How to Split a String in Python [split() & Slicing]

In this post, I will show you some of the ways you can use Python to split a string into smaller pieces, also known as substrings. Splitting a string is a common operation in programming, especially when you need to process text data or user input. Let’s get started!

To split a string in Python, use the split() method. This method takes a separator as an argument and returns a list of substrings that are separated by that separator.

Example

For example, if you want to split a string by whitespace, you can do something like this:

sentence = "The quick brown fox jumps over the lazy dog."
words = sentence.split()
print(words)

This will output:

['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog.']

You can see that the split() method has broken the sentence into a list of words, using whitespace as the separator.

Using Other Separators

You can also specify a different separator, such as a comma, a dash, or any other character. For example, if you want to split a string by commas, you can do something like this:

names = "Alice,Bob,Charlie,Dave"
names_list = names.split(",")
print(names_list)

This will output:

['Alice', 'Bob', 'Charlie', 'Dave']

You can see that the split() method has broken the names into a list of substrings, using commas as the separator.

Alternative Method: Slicing

Another way to split a string in Python is to use slice notation. This is a way of accessing a part of a string by specifying its start and end index. For example, if you want to get the first four characters of a string, you can do something like this:

name = "Harry"
first_four = name[0:4]
print(first_four)

This will output:

Harr

You can see that the slice notation has extracted the substring from index 0 to index 3 (the end index is exclusive) of the name. You can also use negative indexes to count from the end of the string. For example, if you want to get the last three characters of a string, you can do something like this:

name = "Harry"
last_three = name[-3:]
print(last_three)

This will output:

rry

You can see that the slice notation has extracted the substring from index -3 to the end of the name. You can use slice notation to split a string into any number of substrings, as long as you know their start and end indexes.

There are other ways to split a string in Python, such as using regular expressions or loops, but these are more advanced topics that I will cover in another post. For now, I hope you have learned something useful from this post on how to split a string in Python. If you have any questions or feedback, please leave a comment below. Thanks for reading!

Stephen Mclin
Stephen Mclin

Hey, I'm Steve; I write about Python and Django as if I'm teaching myself. CodingGear is sort of like my learning notes, but for all of us. Hope you'll love the content!

Articles: 125

Leave a Reply

Your email address will not be published. Required fields are marked *