尝试将多行字符串大写,但不起作用。有什么想法吗?

Trying to capitalize multiline string, but not working. any thoughts?

text = '''felt happy because I saw the others were happy 
 and because I knew I should feel happy, 
 but I wasn’t really happy.'''

print(text.capitalize())

只有第一个单词大写。

str.capitalize is documented 只将整个字符串的第一个字符大写,其余小写:

str.capitalize()

Return a copy of the string with its first character capitalized and the rest lowercased.

如果要将每个单词的第一个字母大写(将其余字母小写),use .title(); if you want every character to be uppercase, use .upper()

来自official documentation 关于capitalize():

Return a copy of the string with its first character capitalized and the rest lowercased.

您正在寻找的方法是title(),它将每个单词大写。这是来自 the documentation 的描述:

Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.

结果如下:

>>> text = '''felt happy because I saw the others were happy and because I knew I should feel happy, but I wasn’t really happy.'''
>>> print(text.title())

'Felt Happy Because I Saw The Others Were Happy And Because I Knew I Should Feel Happy, But I Wasn’T Really Happy.'