partition method of str class

The partition() method of python str class splits the string into two parts and it returns the part1, separator, part2 as a tuple of string objects.

Str Updated 13 Mar 2017 1 min read

Method Name

partition

Method Signature

partition(separatorChar)

Method Overview

  • The partition method of str class splits a string object into two strings based on the separator character found at the lowest index of the string
  • partition() returns the resulting first token, the separator and the resulting second token as a tuple.

Example1

python
partitionChar       = "@"

string2Partition    = "someone@example.org"

tokens              = string2Partition.partition(partitionChar)

print(tokens)

partitionChar       = "."

tokens              = string2Partition.partition(partitionChar)

print(tokens)

Output

Output
('someone', '@', 'example.org')

('someone@example', '.', 'org')

Example2

python
stockQuote = '"MSFT","65.11","65.26","64.75","16457370"'

seperator  = ","

stringTuple = stockQuote.partition(seperator)

print(stringTuple)

Output

Output
('"MSFT"', ',', '"65.11","65.26","64.75","16457370"')

Example3 – A simple string tokenizer using python’s partition method

python
def tokenise_string(csvString, seperator):

    string2work = csvString

    tokens      = []

    while(True):

        parts = string2work.partition(seperator)

        if parts[0] is not "":

            tokens.append(parts[0])

            string2work = parts[2]

        else:

            break

    return tokens

stockQuote = '"MSFT","68.21","66.36","65.85","15357470"'

tks = tokenise_string(stockQuote,",")

print(tks)

##

Output

Output
['"MSFT"', '"68.21"', '"66.36"', '"65.85"', '"15357470"']