Partition Method Of Str Class

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:

partitionChar       = "@"

string2Partition    = "someone@example.org"

tokens              = string2Partition.partition(partitionChar)

print(tokens)

 

partitionChar       = "."

tokens              = string2Partition.partition(partitionChar)

print(tokens)

 

Output:

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

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

 

 

Example2:

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

seperator  = ","

stringTuple = stockQuote.partition(seperator)

print(stringTuple)

 

 

Output:

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

 

 

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

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:

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

 

 


Copyright 2023 © pythontic.com