Doctest failing
Terry Reedy
tjreedy at udel.edu
Sat Sep 10 13:59:02 EDT 2011
On 9/10/2011 7:20 AM, Tigerstyle wrote:
> Hi guys.
>
> I'm strugglin with some homework stuff and am hoping you can help me
> out here.
We appreciate you saying so instead of hiding that this is homework.
> 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())
The key issue is that you want to treat the first word one way (.title
it) and the rest differently (conditionally .title or not) . So
immediately separate the first from the rest and then process each.
There are at least three ways to do the split. Perhaps I should stop
with this hint, and certainly you should think a bit before reading
further, but here is what I consider to be the most elegant 3.2 code.
.
,
,
,
.
.
.
first, *rest = title.strip().lower().split()
new_title = [first.title()]
for word in rest:
if word not in small_words:
word = word.title()
new_title.append(word)
> return(' '.join(new_title))
doctest.testmod() now passes (there is no 'refactory' here)
> def _test():
> import doctest, refactory
> return doctest.testmod(refactory)
> if __name__ == "__main__":
> _test()
--
Terry Jan Reedy
More information about the Python-list
mailing list