Python String Split List Tutorial

The list is one of the most popular types for the Python programming language. The string is another popular type that consists of multiple characters. A string can be split into a list by providing a separator. The string split() method can be used to split a string into a list. We examine different use cases for the string split() method in this tutorial.

String split() Syntax

String data type provides the split() method which is used to split the string. The split() method has the following syntax.

STRING.split(SEPARATOR,MAXSPLIT)
  • STRING is the string variable or data which will be split.
  • SEPARATOR is the separator character that will be split. This parameter is set in whitespace. This parameter is optional.
  • MAXSPLIT specified how many splits to do. The default value is -1 which means all occurrences. This parameter is optional.

In the following example, we will split the variable named sentence which is a string. It has multiple words separated with whitespaces and we will use the default separator without specifying it. Also, the maxsplit value will be used as default.

sentence = "I like the pythontect.com"

lst = sentence.split()

print(lst)

The output will be like below where every word is set as a list item.

['I', 'like', 'the', 'pythontect.com']

Another popular use case is providing the split characters in order to separate them into list items. In the following example, we will use the comma as the separator.

sentence = "I,like,the,pythontect.com"

lst = sentence.split(",")

print(lst)

The output is like below.

['I', 'like', 'the', 'pythontect.com']

Split List with Comprehension

A list is used to store multiple items which can be a string type. If the string items have some extra characters we want to remove from the split we can use the string split() method. As an example, if the items are like “name,surname” and we want to split the surname and only use the name we can use the list split with comprehension.

students=["ismail,baydan","ahmet,baydan","elif,baydan"]

student_names = [i.split(',')[0] for i in students]

print(student_names)

The output will be like the below. The i.split(‘,’) will split the “ismail,baydan” into a list with two items, and [0] will return the first items with index number 0 which is “ismail”.

['ismail', 'ahmet', 'elif']

Split List with for Loop and List append() Method

The list type can be enumerated with the for loop for each item and these items can be split with the split method and the append() method can be used to add a split string into the new list.

students=["ismail,baydan","ahmet,baydan","elif,baydan"]

student_names=[]

for i in students:
   student_names.append(i.split(',')[0])

print(student_names)

The output will be like the below.

['ismail', 'ahmet', 'elif']

Leave a Comment