0% found this document useful (0 votes)
32 views

Splitting Strings With The Partition Method

The document discusses two string methods in Python - split() and partition(). Split() splits a string into a list of substrings based on a delimiter. Partition() splits a string into a tuple of three elements - the text before the separator, the separator string, and the text after the separator based on the first occurrence of the separator. Examples are provided to demonstrate the usage of both methods on strings.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

Splitting Strings With The Partition Method

The document discusses two string methods in Python - split() and partition(). Split() splits a string into a list of substrings based on a delimiter. Partition() splits a string into a tuple of three elements - the text before the separator, the separator string, and the text after the separator based on the first occurrence of the separator. Examples are provided to demonstrate the usage of both methods on strings.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

>>> 'MyABCnameABCisABCSimon'.

split('ABC')
['My', 'name', 'is', 'Simon']
>>> 'My name is Simon'.split('m')
['My na', 'e is Si', 'on']

A common use of split() is to split a multiline string along the


newline characters. Enter the following into the interactive shell:

>>> spam = '''Dear Alice,


How have you been? I am fine.
There is a container in the fridge
that is labeled "Milk Experiment."

Please do not drink it.


Sincerely,
Bob'''
>>> spam.split('\n')
['Dear Alice,', 'How have you been? I am fine.', 'There is a container in the
fridge', 'that is labeled "Milk Experiment."', '', 'Please do not drink it.',
'Sincerely,', 'Bob']

Passing split() the argument '\n' lets us split the multiline string
stored in spam along the newlines and return a list in which each item
corresponds to one line of the string.

Splitting Strings with the partition() Method


The partition() string method can split a string into the text before and
after a separator string. This method searches the string it is called on
for the separator string it is passed, and returns a tuple of three
substrings for the “before,” “separator,” and “after” substrings. Enter
the following into the interactive shell:
>>> 'Hello, world!'.partition('w')
('Hello, ', 'w', 'orld!')
>>> 'Hello, world!'.partition('world')
('Hello, ', 'world', '!')

If the separator string you pass to partition() occurs multiple times in


the string that partition() calls on, the method splits the string only on
the first occurrence:
>>> 'Hello, world!'.partition('o')
('Hell', 'o', ', world!')

You might also like