Python Split() Function for Strings

Python Split() Function for Strings

6 mins read4.2K Views Comment
clickHere
Updated on Nov 22, 2022 19:17 IST

The below article goes through explaining and implementing split function in python with suitable examples.

2022_06_MicrosoftTeams-image-11.jpg

Split Function in Python

During Python programming, you might come across instances where you would need to break a string into chunks in order to make it convenient to extract specific values from the string. For example, separating the words in a sentence, or dividing a paragraph into phrases. 

We have already discussed how to concatenate a Python list to a string. In this article, we will guide you on how to split strings and create lists using an in-built split() function in Python. So, without further ado, let’s get started!

We will be covering the following sections today:

Python Split() Function Syntax

Here’s the syntax for this predefined string split function in Python:

.split(separator, maxsplit)

Let’s talk about the two arguments passed to the function as you can see in the syntax above:

  • Separator: (Optional) This argument is the delimiter that specifies the character by which the string has to be split. The default separator is the whitespace.
  • Maxsplit: (Optional) This argument provides the number of splits a string should go through. If no value is specified, the string is split based on the delimiter only.

The split() function returns a list object that contains the split strings, called the substrings, as elements. These substrings can be accessed by traversing the list.

split

How to Split a String Using Python Split() Method

Simple string split 

Here, we split the input string into a list of substrings without passing any argument to the split() function:

str = 'Hi! Welcome to Shiksha Online'
print('Original string: ', str)
 
#Split the string with no arguments passed
print('Split string: ', str.split())

Output:

output1

As you can see, the above string has been split into 5 substrings based on the whitespaces as they are the default separator (delimiter) when no argument is passed to the function. 

Split the string based on character occurrence

The split() function splits the given string based on the character that we specify as the separator. For example:

str = 'Shiksha Online'
print('Original string: ', str)
 
#Split the string based on character occurance
print('Split string: ', str.split('a'))

Output:

output2

In the above case, the input string gets split every time the function comes across the character ‘a’ in the string, i.e., 2 times – so, two splits happen to result in three substrings.

Any character can be specified as a separator as long as it occurs within the input string. Let’s look at a few common examples:

The new line character as separator

str = 'Hi! Welcome
to
Naukri
Learning'
print('Original string: ', str)
 
#Split the string by new line character as delimiter
print('Split string: ', str.split('
'))

Output:

output3

The above string consists of three ‘ ’ characters – so, the string gets split thrice to result in four substrings.

The tab as separator

str = 'Hi!	Welcome to Shiksha Online'
print('Original string: ', str)
 
#Split the string by tab as delimiter
print('Split string: ', str.split('	'))

Output:

output4

The above string consists of only one ‘ ’ character – so, the string gets split once to result in two substrings.

The comma as separator

str = 'Hi! Welcome, this is Shiksha Online'
print('Original string: ', str)
 
#Split the string by comma as delimiter
print('Split string: ', str.split(','))

Output:

output5

The above string consists of only one ‘,’ character – so, the string gets split once to result in two substrings.

Split the string with multiple separators

We can also specify multiple characters as separators. For this, we need to make use of the re module of Python and import the re.split() function.

Let’s see how we do it through the below example:

#import the module re
import re
 
str = 'Hi! Welcome, we are @ Shiksha Online'
print('Original string: ', str)
 
#Split the string by multiple delimiters
print('Split string: ', re.split('!|,|@',str))

Output:

output6

In the above example, the re.split() function takes two arguments:

  1. Separator(s): we have specified three characters as separators – ‘!’ and ‘,’ and  ‘@’. All separators are specified with a | in between. Each time any of the given characters come up, the string gets split up. 
  2. String: we pass the string that has to be split as the second argument.

Split the string with a substring as a separator

We can also specify one of the substrings as the separating characters in the split() function.

Let’s see how we do it through the below example:

str = 'Hi! Welcome to Shiksha Online'
print('Original string: ', str)
 
#Split the string by substring as delimiter
print('Split string: ', str.split('to'))
 

Output:

output8

In this case, the above string consists of the word ‘to’ which has been passed as the separator to the function – so, the string gets split up on this word as the character to result in two substrings.

Split the string using maxsplit

As discussed in the previous section, we can specify the number of times we want the splits to occur through the maxsplit argument in the split() function. For example:

str = 'Hi! Welcome this is Shiksha Online'
print('Original string: ', str)
 
#Split the string using Maxsplit
print('Split string: ', str.split(' ',2))

Output:

output9

As you can see, the above string is split up based on the whitespaces as the separator

But in this case, we have also provided the maxsplit parameter as 2 – so, the string gets split only twice to result in three substrings. The rest of the whitespaces are considered a part of the last substring.  

String split to display list items 

Here, we split the input string into a list of substrings without passing any argument to the split() function:

str = 'Naukri#Learning#Python#Blog'
 
#Split the string by hash as delimiter
#and store in a list variable
mylist = str.split('#')
 
#Iterate over the list to extract list items
for i in mylist:
    print(i)

Output:

output9

So, the above example demonstrates how a string can be split into a list of substrings where each substring is an individual item of the list. Here, we have used for loop to iterate over the list items and print them. 

You can also display an individual substring based on its index in the list. Let’s say we only want to display the substring ‘Python’. We just need to tweak the above code a little:

str = 'Naukri#Learning#Python#Blog'
 
#Split the string by hash as delimiter
#and store in a list variable
mylist = str.split('#')
 
print(mylist[2])

Output:

output10

So, we specified the position of our desired substring in the list and printed the item. Easy Peasy!

Endnotes

Python and how to use it to split the strings based on its parameters – separator and maxsplit. We also learned how to access the split substrings by using Python lists. Want to learn more about Python and practice Python programming? Explore related articles here.

Top Trending Tech Articles:
Career Opportunities after BTech | Online Python Compiler | What is Coding | Queue Data Structure | Top Programming Language | Trending DevOps Tools | Highest Paid IT Jobs | Most In Demand IT Skills | Networking Interview Questions | Features of Java | Basic Linux Commands | Amazon Interview Questions

______________

Recently completed any professional course/certification from the market? Tell us what liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio

Comments