首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >除了组合new_title语句之外,如何使用Python3重构此代码?请帮助我:(

除了组合new_title语句之外,如何使用Python3重构此代码?请帮助我:(
EN

Stack Overflow用户
提问于 2011-06-15 10:32:01
回答 1查看 119关注 0票数 0
代码语言:javascript
复制
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'
    """
    lst_of_words = title.lower().split()
    num_of_words = len(lst_of_words)
    if num_of_words < 1:
        return ''
    new_title = lst_of_words.pop(0)
    new_title = new_title[0].upper() + new_title[1:]
    tpl_of_words = tuple(lst_of_words)
    for word in tpl_of_words:
        prep_word = False
        for prep in small_words:
            if prep == word:
                new_title = new_title + ' ' + word
                new_title = new_title + word
                prep_word = True
                break
        if prep_word == True:
            continue
        new_title = new_title + ' '+ word[0].upper()+ word[1:]
        new_title = new_title + word[0].upper()
        new_title = new_title + word[1:]
    return new_title

def _test():
    import doctest, refactory
    return doctest.testmod(refactory)

if __name__ == "__main__":
    _test()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-06-15 10:43:39

代码语言:javascript
复制
return ' '.join((new[0].upper() + new[1:]) if (ix == 0 or new not in small_words)
  else new for (ix, new) in enumerate(title.lower().split()))
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6352394

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档