Capitalize a string

前端 未结 9 735
轻奢々
轻奢々 2020-11-27 19:33

Does anyone know of a really simple way of capitalizing just the first letter of a string, regardless of the capitalization of the rest of the string?

For example:

相关标签:
9条回答
  • 2020-11-27 19:45

    Docs can be found here for string functions https://docs.python.org/2.6/library/string.html#string-functions
    Below code capitializes first letter with space as a separtor

    s="gf12 23sadasd"
    print( string.capwords(s, ' ') )
    

    Gf12 23sadasd

    0 讨论(0)
  • 2020-11-27 19:47

    You can use the str.capitalize() function to do that

    In [1]: x = "hello"
    
    In [2]: x.capitalize()
    Out[2]: 'Hello'
    

    Hope it helps.

    0 讨论(0)
  • 2020-11-27 19:52

    for capitalize first word;

    a="asimpletest"
    print a.capitalize()
    

    for make all the string uppercase use the following tip;

    print a.upper()
    

    this is the easy one i think.

    0 讨论(0)
  • 2020-11-27 19:54
    str = str[:].upper()
    

    this is the easiest way to do it in my opinion

    0 讨论(0)
  • 2020-11-27 19:57

    @saua is right, and

    s = s[:1].upper() + s[1:]
    

    will work for any string.

    0 讨论(0)
  • 2020-11-27 20:02
    s = s[0].upper() + s[1:]
    

    This should work with every string, except for the empty string (when s="").

    0 讨论(0)
提交回复
热议问题