[Pythonmac-SIG] Python Help?

Charles Hartman charles.hartman at conncoll.edu
Thu Jun 2 13:30:48 CEST 2005


On Jun 1, 2005, at 10:33 PM, Matthew S-H wrote:

> ##Seperates words with punctuation into 2 seperate words.
> def puncSep(list):
>     currentWord = -1
>     for word in list:
>         currentWord = currentWord + 1
>         if word[-1] in punctuation:
> #            list = list[:currentWord] + [word[0:-1], word[-1]] +  
> list[currentWord + 1:]
>             list[currentWord:currentWord + 1] = [word[:-1], word[-1]]
>             currentWord = currentWord + 1
>     return list

A couple of problems here (though you'll get better advice from more  
experienced people).

You start with a list of strings, but your code replaces one (or  
more) of them, not with a different string or two strings, but with a  
tuple whose elements are two strings. The comma is what does that.  
Then (I thnk) you're expecting the size of your list to adjust  
itself, so that the index of the last element will be one larger than  
it was before the substitution. But the list's length -- the number  
of elements in the list -- hasn't changed; it's just that one of them  
has been replaced with a tuple, a different kind of object from a  
string.

One easy (not necessarily efficient) way to revise it would be (off  
the top of my head without testing)

         list[currentWord] = word[:-1]
         list.insert(currentWord + 1, word[-1])

(though there are more elegant ways to do it without using the  
currentWord indexing variable).

By the way, "list" is an operator in Python (it turns its argument  
into a list), so it's a bad idea to use that as the name of a variable.

Charles Hartman


-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/pythonmac-sig/attachments/20050602/2cc1a87e/attachment.html


More information about the Pythonmac-SIG mailing list