Skip to content

How to split Python strings?

Concatenating and splitting strings are some of the most common string operations in just about any programming language. There are several scenarios where you might need to break up a string into multiple parts to perform some actions on a said string.

While we’ve already covered how to concatenate strings in Python in a previous article, today, we’re going to take a look at splitting strings. 

Also read: How to create a list in Python?


Splitting strings in Python using the split() method

The split() method in Python returns a list of strings after breaking them up according to the given criteria. The method takes two parameters at most.

  • Separator: This is where you specify the separator where the function is supposed to split the string. By default, the method splits the given string each time it encounters a blank space.
  • Maxsplit: This is a number that tells the method how many times to split the string. If no number is specified, there’s no limit set on separations. 

The output is a list of the separated words or strings. Take a look at this example.

string = 'Candid Technology'
print(string.split())

The above snippet will split the given string into two separate words — ‘Candid’ and ‘Technology’. The split happens when the split() method encounters a blank space as that’s the default separator. 

string = 'Candid.Technology'
print(string.split('.'))

The above snippet will give the following output.

['Candid', 'Technology']

Note that the split happens when the method encounters a period (.) as that’s the separator that we’ve specified when invoking the function. 

You can also specify the number of times you want to split the strings. Look at the below example.

string = 'Candid.Technology.Tech.Made.Simpler'
print(string.split('.', 2)

The above snippet will output the following list. 

['Candid', 'Technology', 'Tech.Made.Simpler']

As you can see, only two words were split, at the given separator. 

Also read: How to run Python in terminal?

Hello There!

If you like what you read, please support our publication by sharing it with your friends, family and colleagues. If you're running an Adblocker, we humbly request you to whitelist us.

Share on facebook
Share on whatsapp
Share on twitter
Share on reddit
Share on linkedin
Share on pocket
Share on pinterest
Share on telegram
Share on stumbleupon
Share on digg
Share on tumblr
Share on email
Share on skype
Share on xing
Share on vk
Share on odnoklassniki
Share on mix








>