Python title() with apostrophes

后端 未结 5 2028
不思量自难忘°
不思量自难忘° 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:53

    IMHO, best answer is @Frédéric's one. But if you already have your string separated to words, and you know how string.capwords is implemeted, then you can avoid unneeded joining step:

    def capwords(s, sep=None):
        return (sep or ' ').join(
            x.capitalize() for x in s.split(sep)
        )
    

    As a result, you can just do this:

    # here my_words == ['word1', 'word2', ...]
    s = ' '.join(word.capitalize() for word in my_words)
    

提交回复
热议问题