[Tutor] how to split/partition a string on keywords?

eryksun eryksun at gmail.com
Fri Aug 24 00:16:54 CEST 2012


On Thu, Aug 23, 2012 at 5:25 PM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> To use partition just call it repeatedly until the last string is empty. As
> ever the >>> prompt is your friend:
>
>>>> st = 'here we go and there you are and we all go roundabout'
>>>> h,s,t = st.partition(' and')
>>>> results = [h,s]
>>>> while t:
> ...    h,s,t = t.partition(s)
> ...    results += [h,s]
> ...

The keyword needs a space at both ends:

    >>> st = 'an androphobic andromedan android'
    >>> h,s,t = st.partition(' and')
    >>> results = [h,s]
    >>> while t:
    ...     h,s,t = t.partition(s)
    ...     results += [h,s]
    ...
    >>> results
    ['an', ' and', 'rophobic', ' and', 'romedan', ' and', 'roid', '']

> Finally you can also find a solution using regular expressions, but they
> shouldn't be needed for something like this.

It depends on how flexible it needs to be about common whitespace
characters (space, tab, new line, carriage return) and punctuation.
But this should be fine for raw_input. Tabs and punctuation could be
replaced with spaces beforehand if necessary. Otherwise it won't
partition a sentence on " and " such as, "I want an omelet--and some
hash browns."


More information about the Tutor mailing list