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

akleider at sonic.net akleider at sonic.net
Fri Aug 24 00:08:58 CEST 2012


This question seemed a good excercise so I banged out a little script
(which worked) but latter I saw posts showing code that by using string
method 'partition' provided a more elegant solution.
I was previously unaware of this method.  My "bible" has been David M.
Beazley's Python Essential Reference (3rdEd) in which this method is not
mentioned (that I can see.)
Should I switch "bibles?"
(I often find myself wanting to hack in "off line environments" so
something as old fashion as a book would be nice:-)

Here's my script for what it's worth:

#!/usr/bin/env python

import sys

usage = """test0 separator
Requires one parameter, the text to be used to separate the input which
will be requested by the program."""

if len(sys.argv) != 2:
    print usage
separator = sys.argv[1]

def separate(string, separator):
    ret = []
    i = string.find(separator)
    l = len(separator)
    while i > 0:
        ret.append(string[:i])
        ret.append(separator)
        string = string[i+l:]
        i = string.find(separator)
    ret.append(string)
    return ret

def repart(string, separator):
    """Does the same as separator but using string method 'partition'"""
    parts = string.partition(separator)
    if parts[0] == string:
        return (parts[0], )
    else:
        return parts[:-1] + repart(parts[-1], separator)

input_str = raw_input("Enter text to split on '%s': "%(separator, ))

separated_array = separate(input_str, separator)
for s in separated_array:
    print s
parted_array = repart(input_str, separator)
for s in parted_array:
    print s




 > Hi all,
> I'm new to programming and Python.
> I want to write a script that takes a string input and breaks the string
> at
> keywords then outputs the pieces on separate lines.
> I'm not sure how to break the string, though.
> I looked through the docs and found split() and partition(), which come
> close.
> But split() doesn't retain the separator and partition() retains the white
> space and returns a 3-tuple which I'll have to figure out how to rejoin
> nor
> does it partition on subsequent instances of the separator.
>
> Here's the script in its basic form:
>
> #!/usr/bin/python
>
> text = raw_input("Enter text: ")
> print "You entered ", text
>
> objects = text.partition(' and')
> print objects
>
> for object in objects:        # Second Example
>
>    print object
>
> For example, if I run this with the input:
> "Ham and cheese omelette with hasbrowns and coffee."
> I get:
> Ham
>  and
>  cheese omelette with hashbrowns and coffee.
>
> Any help is greatly appreciated.
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>




More information about the Tutor mailing list