Python Parse String Tutorial

Python provides the split() method by default in order to parse string values and literals in different ways. The split() method can be used to parse strings with single or more characters like commas, points, etc. In this tutorial, we examine how to parse the string using the split() method.

split() Method Syntax

The split() method has the following syntax. The split() method can be used with string variables or string literals without a problem. The parsed items are returned as a single list.

STRING.split(SEPARATOR,MAX_SPLIT)
  • SEPARATOR is the separator string that consists of single or more characters.
  • MAX_SPLIT is used to set how many times the STRING will be split with the SEPARATOR. By default whole STRING is split but by using the MAX_SPLIT the split count can be limited.

Parse String with Spaces

One of the most popular separators used to parse strings in the space. The space can be used to parse a sentence into words.

s = "I love Pythontect.com"

s_list = s.split(" ")

print(s_list)
Parse String with Spaces

Parse String with Commas

The comma can be used to parse a string like the one below.

s = "I,love,Pythontect.com"

s_list = s.split(",")

print(s_list)

Parse String with Points

The point can be used to parse a string like the one below.

s = "I.love.Pythontect.com"

s_list = s.split(".")

print(s_list)

Parse String with Underscore

The underscore can be used to parse a string like the below.

s = "I_love_Pythontect.com"
s_list = s.split("_")

print(s_list)

Specify Split Count

By default, the string is parsed without any limit with the specified separator. But we can limit the split count and not split the whole string. In the following example, we parse only a one-time sentence with the space separator.

s = "I love Pythontect.com"
s_list = s.split(" ",1)

print(s_list)
['I', 'love Pythontect.com']

Leave a Comment