将字符串的首字母大写而不触碰其他字母 [英] Capitalize the first letter of a string without touching the others
本文介绍了将字符串的首字母大写而不触碰其他字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想大写一个字符串的拳头字母,但剩下其余的
I'm wanting to capitalize the fist letter of a string but leave the rest
我所拥有的:
racEcar
What I have: racEcar
我想要什么:
RacEcar
What I want: RacEcar
推荐答案
您应该像Martijn建议的那样做,但是为了使您的函数更健壮,请切成第一个字母,这样就不会在空字符串上出错:
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:]
然后:
>>> capfirst(rc)
'RacEcar'
>>> capfirst('')
''
这篇关于将字符串的首字母大写而不触碰其他字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文