Python String split() Method
Python String split() slices a string by specifying the separator, or by num+1 substrings if the second argument, num, has the specified value.
Python String split() Syntax
Split() method syntax.
str.split(str="", num=string.count(str))
Python String split() Parameters
- str – the separator, defaults to all empty characters, including spaces, line feeds (\n), tabs (\t), etc.
- num – the number of separations. Defaults to -1, i.e. separates all.
Python String split() Return Value
Return the list of split strings.
Python String split() Example#1
The following example demonstrates the use of the split() function.
#!/usr/bin/python3
str1 = "this is string example from apidemos.com....wow!!!"
print (str1.split( )) # Separated by spaces
print (str1.split('i',1)) # Separated by i
print (str1.split('w')) # Separated by w
Output:
Python String split() Example#2
The following example demonstrates how the split() function works when maxsplit is specified.
The maxsplit parameter is used to control how many splits to return after parsing the string. Even though there may be multiple splits, it only does the maximum number of splits defined by the maxsplit parameter.
word = 'api, for, demos, good examples.'
# maxsplit: 0
print(word.split(', ', 0))
# maxsplit: 4
print(word.split(', ', 4))
# maxsplit: 1
print(word.split(', ', 1))
Output:
Python String split() Example#3
URL simple segmentation.
When we learn to crawl in python, for example, we need to save images and get the names of the images, we can follow the following method.
#!/usr/bin/python3
url = "https://www.apidemos.com/python/image/123456.jpg"
# Separated by .
path =url.split(".")
print(path)
Output:
Separated by /
.
#!/usr/bin/python3
url = "https://www.apidemos.com/python/image/123456.jpg"
#Separated by /
path =url.split("/")
print(path)
Output:
When learning to crawl in python, for example, we need to save images and get the names of the images, we can follow the following method.
#!/usr/bin/python3
url = "https://www.apidemos.com/python/image/123456.jpg"
#Separated by /
path =url.split("/")[-1]
print(path)
Output: