Skip to Content

6 Useful Examples to Master Python String Split method

The split() method separates a string into parts wherever it finds a space and stores all the parts of the string in a list in Python.

The split method returns a list of all the words of the string separated by a delimiter and the num integer specifies the maximum splits.

If num is not specified, then all the possible splits are made.

If we don’t specify a separator, split() uses any sequence of white space characters—newlines, spaces, and tabs.

String split Description

Python string method split() returns a list of all the words in the string, using str as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to num.

String split Syntax

Following is the syntax for split() method

str.split(str=””, num=string.count(str))

String Split Parameters

  • str − This is any delimeter, by default it is space.
  • num − It is a number, which tells us to split the string into maximum of provided number of times.

String Split Return Value

This method returns a list of lines.

String Split by space

>>> sentence = “Google Cloud Platform lets you build, deploy, and scale applications, websites, and services on the same infrastructure as Google.”

>>> sentence.split()

[‘Google’, ‘Cloud’, ‘Platform’, ‘lets’, ‘you’, ‘build,’, ‘deploy,’, ‘and’, ‘scale’, ‘applications,’, ‘websites,’, ‘and’, ‘services’, ‘on’, ‘the’, ‘same’, ‘infrastructure’, ‘as’, ‘Google.’]

String Split by other separator

>>> sentence = “Google Cloud Platform lets you build, deploy, and scale applications, websites, and services on the same infrastructure as Google.”

>>> sentence.split(‘,’)

[‘Google Cloud Platform lets you build’, ‘ deploy’, ‘ and scale applications’, ‘ websites’, ‘ and services on the same infrastructure as Google.’]

>>> str1 = “27-12-2016”
>>> str1.split(“-“)
[’27’, ’12’, ‘2016’]
>>>

String Split with num

>>> str1 = “27-12-2016”
>>> str1.split(“-“, 1)
[’27’, ’12-2016′]
>>> str1.split(“-“, 2)
[’27’, ’12’, ‘2016’]
>>> str1 = “27-12-2016-2017-2018”
>>> str1.split(“-“, 2)
[’27’, ’12’, ‘2016-2017-2018’]

String Split with one word

>>> cloud= “Google Cloud Platform lets you build, deploy, and scale applications, websites, and services on the same infrastructure as Google.”
>>> cloud.split(‘you’)
[‘Google Cloud Platform lets ‘, ‘ build, deploy, and scale applications, websites, and services on the same infrastructure as Google.’]

String Split with Two Delimiters in Python

Python’s built-in module re has a split() method we can use for this case.

Let’s use a basic a or b regular expression (a|b) for separating our multiple delimiters.

import re

text = “python is, an easy;language; to, learn.”
print(re.split(‘; |, ‘, text))