Python Split() Function for Strings
The below article goes through explaining and implementing split function in python with suitable examples.
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.
Best-suited Python courses for you
Learn Python with these high-rated online courses
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:
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:
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\nto\nNaukri\nLearning' print('Original string: ', str) #Split the string by new line character as delimiter print('Split string: ', str.split('\n'))
Output:
The above string consists of three β\nβ characters β so, the string gets split thrice to result in four substrings.
The tab as separator
str = 'Hi!\tWelcome to Shiksha Online' print('Original string: ', str) #Split the string by tab as delimiter print('Split string: ', str.split('\t'))
Output:
The above string consists of only one β\tβ 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:
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:
In the above example, the re.split() function takes two arguments:
- 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.
- 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:
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:
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:
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:
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.
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