Python title() with apostrophes

后端 未结 5 2029
不思量自难忘°
不思量自难忘° 2020-12-16 09:06

Is there a way to use .title() to get the correct output from a title with apostrophes? For example:

\"john\'s school\".title() --> \"John\'S         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 09:57

    Although the other answers are helpful, and more concise, you may run into some problems with them. For example, if there are new lines or tabs in your string. Also, hyphenated words (whether with regular or non-breaking hyphens) may be a problem in some instances, as well as words that begin with apostrophes. However, using regular expressions (using a function for the regular expression replacement argument) you can solve these problems:

    import re
    
    def title_capitalize(match):
        text=match.group()
        i=0
        new_text=""
        capitalized=False
        while i

    Anyway, you can edit this to compensate for any further problems, such as backticks and what-have-you, if needed.

    If you're of the opinion that title casing should keep such as prepositions, conjunctions and articles lowercase unless they're at the beginning or ending of the title, you can try such as this code (but there are a few ambiguous words that you'll have to figure out by context, such as when):

    import re
    
    lowers={'this', 'upon', 'altogether', 'whereunto', 'across', 'between', 'and', 'if', 'as', 'over', 'above', 'afore', 'inside', 'like', 'besides', 'on', 'atop', 'about', 'toward', 'by', 'these', 'for', 'into', 'beforehand', 'unlike', 'until', 'in', 'aft', 'onto', 'to', 'vs', 'amid', 'towards', 'afterwards', 'notwithstanding', 'unto', 'while', 'next', 'including', 'thru', 'a', 'down', 'after', 'with', 'afterward', 'or', 'those', 'but', 'whereas', 'versus', 'without', 'off', 'among', 'because', 'some', 'against', 'before', 'around', 'of', 'under', 'that', 'except', 'at', 'beneath', 'out', 'amongst', 'the', 'from', 'per', 'mid', 'behind', 'along', 'outside', 'beyond', 'up', 'past', 'through', 'beside', 'below', 'during'}
    
    def title_capitalize(match, use_lowers=True):
        text=match.group()
        lower=text.lower()
        if lower in lowers and use_lowers==True:
            return lower
        else:
            i=0
            new_text=""
            capitalized=False
            while i

提交回复
热议问题