split(delimiter, max splits)
split() function is called upon a string object and takes two optional parameters, and returns a list of substrings as the output.
Parameters:
- Delimiter: Optional parameter where splitting takes place. If no parameter is given, then the string is split on whitespace characters’ encounter (space, tabs, newline). If a separator or delimiter is provided, then splitting will be done on this delimiter.
- Max splits: Optional parameter, which specifies the maximum number of splits. Default is -1, which means there is no limit on the number of splits.
“Ready to take your python skills to the next level? Sign up for a free demo today!”
Definition
The split() method splits a string into a list using a user specified separator. When a separator isn’t defined, whitespace(” “) is used.
String factors are valuable tools for every Python software programmer. Also, they can contain numeric or alphanumeric data and are normally used to store information indexes or print messages. However, the .split() Python work is a normally utilized string control tool.
If you have tried connecting two strings in Python by order, at that point split() does the specific inverse of that. Sooner or later, you may need to separate a long string into little strings. Also, this is something different to the link which unions or joins strings into one.
To do this, you utilize the split(). However, the main job of this is to divide or separate a string and add the information to a string array utilizing a characterized separator.
What is a String?
Python doesn’t have a character information type, a single character is additionally considered as a string. We utilize the single or double statements to indicate a string. To get to a string, we utilize the indexes and square brackets. Since strings are variable in nature, we can’t make any changes once we have declared a string.
name = “Codeavail”
print(name[0])
Output: C
after the declaration we cannot change a string, in Python we can split a string.
“Experience the power of our web development course with a free demo – enroll now!”
Examples of Split Function in Python
Given below are the examples of Split Function in Python:
Example #1
Python program to illustrate the functioning of the split() function.
Code:
# split () taking different delimiters
# 1 --> no delimiter specified
inp1 = 'A E I O U'
print("string will split at whitespace :",inp1.split())
print("list of vowels :")
for i in inp1.split():
print(i)
print('\n')
# 2 --> delimiter is comma and a space (, )
inp2 = 'J&K, Puducherry, Delhi, Andamana and Nicobar, Chandigarh, Dadra and Nagar Haveli, Daman and Diu, Lakshadweep, Ladakh'
ut = inp2.split(', ')
print("Number of Union Territories :", len(ut))
print("UT is listed as below :")
for u in range(len(ut)):
print((u+1),'-->', ut[u])
print('\n')
# 3 --> delimiter is |
inp3 = 'java|python|c++|scala|julia'
print("string will split at '|' :", inp3.split('|'))
print("Different programming languages are :")
for lang in inp3.split('|'):
print(lang)
print('\n')
# 4 --> splitting string at every 4 character
inp4 = 'fourfivenine'
print([inp4[i: i+4] for i in range(0, len(inp4), 4)])
Explanation:
In the above program, the split() function is called on four different input strings with different delimiters, and the max split optional parameter is taking its default value -1.
1. The first delimiter is the default one, i.e. whitespaces.
Output: List containing vowels which are then traversed using for loop.
2. The second delimiter is a comma followed by a space, i.e. ‘, ‘
Input string: String containing all the Union territories in India separated by a comma and space.
Output: List containing different UTs. Each UT is then printed using for loop.
3. The third delimiter is pipe, i.e.
Input string: String containing different programming languages separated by delimiter |
Output: List of different languages.
4. Final string ‘fourfivenine’ is split at every 4th. This split is done using list comprehension.
Output:
“Get hands-on with our python course – sign up for a free demo!”
Example #2
Split() function with optional parameter ‘max splits’.
Code:
# split() function with different values for max splits
print("split() with default max split values i/e -1 :")
inp1 = 'Java@Python@C++@Scala@Julia'
print("input string will split at @ :", inp1.split('@'))
print('\n')
print("number of splits (0):", inp1.split('@', 0))
print("number of splits (1):", inp1.split('@', 1))
print("number of splits (2):", inp1.split('@', 2))
print("number of splits (3):", inp1.split('@', 3))
print("number of splits (4):", inp1.split('@', 4))
print("number of splits (5):", inp1.split('@', 5))
print('\n')
print("split using for loop")
for i in range(6):
print("number of splits", i, inp1.split('@', i))
Output:
Explanation:
In above program, split(sep=’@’, maxsplits= <different values>) is used.
- First, the input string is split at ‘@’ with the default value for max split, i.e. -1. It means all the possible splits are returned.
- The string is then split at ‘@’ with different max_splits values, i.e. 0, 1, 2, 3, 4, 5.
- The same program can be written in a concise manner using for loop.
Example #3
Calculating the sum of marks scored by a student.
Code:
# calculating sum of marks of a student
# input string containing marks scored by a student in five different subjects
marks = '95, 92, 82, 92, 98'
sum = 0
# input string will split at ', '
list_marks = marks.split(', ')
print("marks scored by student :", list_marks)
print("student marks:")
for marks in list_marks:
print(marks)
print('\n')
# calculating total marks
for i in range(len(list_marks)):
sum += int(list_marks[i])
print("total marks scored by student :", sum)
Output:
Explanation:
- The input string is a string of marks obtained by the student in five different subjects separated by delimiter ‘, ‘
- The input string is then split at ‘, ‘ using the split() function.
- The output of split() is a list in which each element represents single subject marks.
- The output list is traversed using for loop.
- The sum of total marks is then calculated and printed as output.
“Ready to take your python skills to the next level? Sign up for a free demo today!”
Why There is Need For Python Split Function
The split function returns the number of strings after breaking the string on the basis of the provided separator. Following are the benefits of utilizing a split function in python:
- At some point we may have to split the long string into shorter strings.
- It is the reverse of the order, which combines two strings together.
- The white spaces are recognized as a divider if none is given in the split function.
- It becomes more accessible to examine and decrease conclusions.
- It accommodates decoding encrypted strings.
How to use Split() in Python with example?
Split function splits down a long string and produces a list with little strings. Below we have mentioned an example for splitting a string in python.
a = “We are Codeavail, we are here for your help”
print(a.split())
Output: [ ‘We’ , ‘are’ , ‘Codeavail’ , ‘we’ , ‘are’ , ‘here’ , ‘for’ , ‘your’ , ‘help’]
This is a simple example to show you how split functions work for breaking down the larger string. Above is a simple example to show how a split function can be used to break down the whole text into smaller strings. To optimize the execution split function has many parameters.
Split Parameters
- Separator – It serves as a delimiter, the string is separated according to the separator defined. It is optional as well if the separator is not specified, the white space will be the default separator.
- Max – It represents the many splits that will take place. The default value is -1 which means there are no limits on the number of the split.
Separator
Below we have given one example to explain split function with a separator parameter:
a = “The man was running faster then the dog, that’s why dog stop running”
print(a.split(” , “)
b = “One*Two*Three*Four*Five*Six*Seven”
print(a.split(” * “)
Output: [ ‘The man was running faster than the dog’ , ‘that’s why dog stop running’ ] [‘One’ , ‘Two’ , ‘Three’ , ‘Four’ , ‘Five’ , ‘Six’ , ‘Seven’ ]
Max
Below is an example to show the split function with a max parameter:
a = “Python*is*my*name”
print(a.split(” * ” , 3)
Output : [ ‘Python’ , ‘is’ , ‘my’ , ‘name’ ]
The parameter of max in the above example is set to 3, which means the output will have 4 elements in the strings list.
When you call upon the function , If there is no separator is determined, whitespace will be utilized by default. In more simplistic terms, the separator is a fixed character that will be located between every variable. The split behavior on a vacant string depends on the value of sep. If sep is not specified, or specified as None, the result will be an empty list. As any string if sep is defined, the outcome will be a list including one element which is an empty string.
“Experience the power of our web development course with a free demo – enroll now!”
For Example
Below are a few examples, where we can use the split function to split the string into smaller chunks or strings.
a = “my name is Codeavail”
print(a.split())
b = “OneTwoThreeFourFiveTap”
print([b[ i : i+3] for i in range(0 , len(b) , 3)])
c = “#Guido#van#rossum#created#the#Python”
print(c.split(” #”, 6)
d = ” this , will , be , in , output, this will be not”
print(d.split(” , ” , 4)
Output: [ ‘my’ , ‘name’ , ‘is’ , ‘python’ ] [‘Cat’ , ‘Dog’ , ‘Ant’ , ‘Car’ , ‘Tap’ ] [‘python’ , ‘was’ , ‘made’ , ‘by’ , ‘Guido’ , ‘van’ , ‘rossum’ ] [‘this’ , ‘will’ , ‘be’ , ‘in’ , ‘output’ ]
Conclusion split() in python
In this article, we have mentioned all the essential information on How To Use Split Function In Python with Example. We hope that all the information is enough to learn the split function in python. You have seen how the split function is used to break down the large string into the smaller string. The string is a permanent data that cannot be changed once you declared it. Although by using split function manipulation can be done.
As a result, if you need programming help to learn split function in python more deeply or help with python programming, and any other programming language, You can contact us through live chat, call, or email anytime, and from anywhere in the world we are available 24*7. Our experts provide the best quality Python Programming assignment help every time.
“Get hands-on with our python course – sign up for a free demo!”