标题中的字符串带有例外

发布于 2021-01-29 19:20:59

有没有在Python的标准方式标题字符的字符串(即词开始大写字符,所有剩余的套管字符有小写),但像离开的文章andinof小写?

关注者
0
被浏览
53
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这有一些问题。如果使用拆分和合并,则某些空格字符将被忽略。内置的大写和标题方法不会忽略空格。

    >>> 'There     is a way'.title()
    'There     Is A Way'
    

    如果句子以文章开头,则不希望标题的第一个单词小写。

    请记住以下几点:

    import re 
    def title_except(s, exceptions):
        word_list = re.split(' ', s)       # re.split behaves as expected
        final = [word_list[0].capitalize()]
        for word in word_list[1:]:
            final.append(word if word in exceptions else word.capitalize())
        return " ".join(final)
    
    articles = ['a', 'an', 'of', 'the', 'is']
    print title_except('there is a    way', articles)
    # There is a    Way
    print title_except('a whim   of an elephant', articles)
    # A Whim   of an Elephant
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看