6 Python 3 String Split Method Examples

Table of Contents

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

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.

Split a string separated 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.’]

Split a string separated 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’]
>>>

Split a string 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’]

Split a string 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.’]

Split a string 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))

 

 

 

Table of Contents

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

You might also like