Quick Reach
Python String Split method
The Python split method breaks the given string. The given string breaks from the specified separator and returns a list of lines.
In this chapter, you will learn the Split string method and a few examples of using it.
How to use the Split method?
Following is the general syntax of the Split method:
String.split(separator, number_of_lines)
For example
Str.split(‘ , ’ , 2)
If no separator is given, space will be used by default.
Split string method example
The example below uses the split method that breaks the string from comma in the given string and displays the output.
1
2
3
4
5
|
#Python Strings methods
strmet = “This is Python strings lesson, this is split string method”
print (strmet.split(‘,’))
|
The output:
[‘This is Python strings lesson’, ‘ this is split string method’]
String split with number parameter example
The following example limits the number of “splits” by using a number as a parameter in the split method. Even the given string has two commas, the split method will break it into two lines while the second line contains a comma. See the example and output below.
1
2
3
4
5
|
#Python Strings methods
strmet = “This is Python strings lesson, this is python split string method, with number parameter”
print (strmet.split(‘,’ , 1 ))
|
The output will be:
[‘This is Python strings lesson’, ‘ this is python split string method, with number parameter’]
Iterating over broken strings
As such, the Python split method returns a list of lines, this can be manipulated just like Python lists. The following example uses a for loop to iterate through the returned broken string.
1
2
3
4
5
6
7
8
9
|
#Python Strings methods
strmet = “This is Python strings lesson, this is python split method, with the number parameter”
lststr = strmet.split(‘,’,2)
for i in lststr:
print (i)
|
The output will be:
This is Python strings lesson
this is python split method
with the number parameter
Leave A Comment?