【问题标题】:Trying to capitalize multiline string, but not working. any thoughts?尝试将多行字符串大写,但不起作用。有什么想法吗?
【发布时间】:2019-05-20 13:54:10
【问题描述】:
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())

只有第一个单词大写。

【问题讨论】:

    标签: python python-3.x capitalization capitalize


    【解决方案1】:

    来自official documentation关于capitalize()

    返回第一个字符大写的字符串副本 其余小写。

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

    返回字符串的标题版本,其中单词以大写字符开头,其余字符为小写。

    结果如下:

    >>> 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.'
    

    【讨论】:

      【解决方案2】:

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

      str.capitalize()

      返回第一个字符大写,其余小写的字符串副本。

      如果要将每个单词的首字母大写(其余字母小写),use .title();如果你希望每个字符都是大写,use .upper()

      【讨论】:

        猜你喜欢
        • 2011-12-06
        • 1970-01-01
        • 1970-01-01
        • 2017-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-31
        • 1970-01-01
        相关资源
        最近更新 更多