Python String split() Method

The split() method divides a string into a list of words using the optional delimiter string argument. You often want to split a string into a list to manipulate the content.

Syntax:

stringvar.split(separator, maxsplit)

This method accepts two optional parameters as follows.

Parameter Description
separator(optional): The separator is the delimiter character or string of characters and is optional, and a string is broken exactly where the separator has occurred in the string. If separator is not mentioned, the white space is treated as the default separator.
maxsplit(optional): The list splits up to length maxsplit times and returns a list of (maxsplit + 1) items long. The last item will contain the rest of the string if the maxsplit specified is less than the length of the items. If the maxsplit is more than the length of the items, then the whole string is broken.

The following example splits the string.

			

vegetables = "tomato, potato, cabbage, cucumber, brinjal" 
vegetables_list = vegetables.split(", ")
for x in range(len(vegetables_list)):
    print(vegetables_list [x])

				

Output:

tomato potato cabbage cucumber brinjal

The following ocde is the example of code breaks the sentence into the words. The default seperator is used.

			

str = "Tutorials Nation: Online Programming Tutorials" 
words= str.split()
print(words)

				

Output:

['Tutorials', 'Nation:', 'Online', 'Programming', 'Tutorials']

How to find the file extension name using the Python split() method?

			

# Specify the file to copy.
file_name = 'harry_potter.jpg'

# get the file extension.
file_parts = file_name.split('.')
print(file_parts[1])

				

Output:

jpg

The Python split() method breaks the filename in two at the dot, so name_ parts[0] contains Harry Potter, and name_parts[1] contains Jpg.

In the following example, the split() method returns the first and last names of a person.

			

# The person's name.
your_name = 'Harry Potter'

# get the two parts.
name_parts = your_name.split(' ')
print(name_parts[0])
print(name_parts[1])

				

Output:

Harry Potter

We can find the difference between a person's birth date and the current date using the split method to ascertain the age.

			

from datetime import datetime  #import datetime module
now = datetime.now() # current date and time
today = now.strftime("%Y-%m-%d").split('-')  # split the current date
dob = '1990-05-01'
born = dob.split("-") 
print("age is about", int(today[0]) - int(born[0]), "years") 

				

Output:

age is about 32 years