On Sat, 10 Sep 2011 04:20:17 -0700, Tigerstyle wrote:

> Hi guys.
> 
> I'm strugglin with some homework stuff and am hoping you can help me out
> here.
> 
> This is the code:
> 
> small_words = ('into', 'the', 'a', 'of', 'at', 'in', 'for', 'on')
> 
> def book_title(title):
>     """ Takes a string and returns a title-case string. All words EXCEPT
>     for small words are made title case unless the string starts with a
>     preposition, in which case the word is correctly capitalized.
>     >>> book_title('DIVE Into python')
>     'Dive into Python'
>     >>> book_title('the great gatsby')
>     'The Great Gatsby'
>     >>> book_title('the WORKS OF AleXANDer dumas')
>     'The Works of Alexander Dumas'
>     """
>     new_title = []
>     title_split = title.strip().lower().split()
>     for word in title_split:
>         if title_split[0] in small_words:
>             new_title.append(word.title())
>         elif word in small_words:
>             new_title.append(word.lower())
>         else:
>             new_title.append(word.title())
>     return(' '.join(new_title))
> 
> def _test():
>     import doctest, refactory return doctest.testmod(refactory)
> if __name__ == "__main__":
>     _test()
> 
> All tests are failing even though I am getting the correct output on the
> first two tests. And the last test still gives me "Of" instead of "of"
> 
> Any help is appreciated.
> 
> Rgds
> 
> T

Ignoring the docttests my process would be to process each word & then 
manually capitalize he 1st word, .I would als0 use a comprehension as 
makes for cleaner code:-

small_words=('into','the','a','of','at','in','for','on')

def capitalize(word):
    if word in small_words:
        return word
    else:
        return word.title()

def set_title(phrase):
    result=[ capitalize(x.lower()) for x in phrase.split(' ') ]
    result[0]=result[0].title()
    return " ".join(result)


print set_title('the works of alexander dumas')


-- 
... I don't like FRANK SINATRA or his CHILDREN.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to