Doctest failing

Peter Otten __peter__ at
Sat Sep 10 22:49:13 CEST 2011

Terry Reedy wrote:

> On 9/10/2011 7:47 AM, Peter Otten wrote:
>> You can work around that with a
>> flag along these lines
>> first = True
>> for word in title_split:
>>      if first:
>>          # special treatment for the first word
>>          first = False
>>      else:
>>          # put checks for all words but the first here
>>      new_title.append(fixed_word) # assuming you have stored the
>>      titlecased
>>                                   # or lowercased word in the fixed_word
>>                                   # variable
> An alternative to a flag and testing every item is to remove and process
> the first item *before* the loop. See my response on this thread or my
> new thread
> Idioms combining 'next(items)' and 'for item in items:'

I reckoned the approach with the flag the most beginner-friendly because you 
don't have to think too hard about the corner-cases, namely

>>> book_title("")

When I use the "process first item before the loop" approach I usually end 
up with a helper generator

def _words(words, small_words={w.title(): w for w in small_words}):
    yield next(words)
    for word in words:
        yield small_words[word] if word in small_words else word

def book_title(s):
    return " ".join(_words(iter(s.title().split())))

and the nagging thought that I'm making it more complex than need be.

More information about the Python-list mailing list