Titlecasing a string with exceptions

前端 未结 9 1652
栀梦
栀梦 2020-11-28 06:28

Is there a standard way in Python to titlecase a string (i.e. words start with uppercase characters, all remaining cased characters have lowercase) but leaving articles like

9条回答
  •  时光说笑
    2020-11-28 06:54

     not_these = ['a','the', 'of']
    thestring = 'the secret of a disappointed programmer'
    print ' '.join(word
                   if word in not_these
                   else word.title()
                   for word in thestring.capitalize().split(' '))
    """Output:
    The Secret of a Disappointed Programmer
    """
    

    The title starts with capitalized word and that does not match the article.

提交回复
热议问题