Capitalize the first letter of a string without touching the others

给你一囗甜甜゛ 提交于 2020-01-17 02:21:11

问题


I'm wanting to capitalize the fist letter of a string but leave the rest

What I have: racEcar

What I want: RacEcar


回答1:


Then just capitalize the first letter with str.upper() and concatenate the rest unchanged

string[0].upper() + string[1:]

Demo:

>>> string = 'racEcar'
>>> string[0].upper() + string[1:]
'RacEcar'



回答2:


You should do like Martijn suggests, but to make your function more robust, slice up to the first letter, so that you don't error on an empty string:

>>> rc = 'racEcar'
>>> newrc = rc[:1].upper() + rc[1:]
>>> newrc
'RacEcar'

so define a function that does this:

def capfirst(s):
    return s[:1].upper() + s[1:]

and then:

>>> capfirst(rc)
'RacEcar'
>>> capfirst('')
''



回答3:


This has already been stated but I decided to show it.

Using capitalize() does what you want without extra work. For example,

def Cap1(string):
    # will not error if empty, and only does the first letter of the first word.
    return string.capitalize()

Using title() may require extra work if you have multiple words. For example,

let's assume your string is: "i want pizza"

def cap2(string):
    return string.title()

The output would be: "I Want Pizza"

Another way you can use upper() is:

def cap3(string):
    if not len(string) == 0: 
        return string[0].upper()


来源:https://stackoverflow.com/questions/31767622/capitalize-the-first-letter-of-a-string-without-touching-the-others

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!