我知道.capitalize()将字符串的第一个字母大写,但如果第一个字符是整数怎么办?

this

1bob
5sandy

这个

1Bob
5Sandy

当前回答

这与@Anon的答案相似,因为它保留了字符串的其余大小写,而不需要re模块。

def sliceindex(x):
    i = 0
    for c in x:
        if c.isalpha():
            i = i + 1
            return i
        i = i + 1

def upperfirst(x):
    i = sliceindex(x)
    return x[:i].upper() + x[i:]

x = '0thisIsCamelCase'

y = upperfirst(x)

print(y)
# 0ThisIsCamelCase

正如@Xan指出的那样,该函数可以使用更多的错误检查(例如检查x是否是一个序列-但是我省略了边缘情况以说明该技术)

每个@normanius评论更新(谢谢!)

感谢@GeoStoneMarten指出我没有回答这个问题!固定,

其他回答

你可以使用regex替换每个单词的第一个字母(前面有一个数字):

re.sub(r'(\d\w)', lambda w: w.group().upper(), '1bob 5sandy')

output:
 1Bob 5Sandy

如果第一个字符是整数,则第一个字母不会大写。

>>> '2s'.capitalize()
'2s'

如果你想要这个功能,去掉数字,你可以使用'2'.isdigit()来检查每个字符。

>>> s = '123sa'
>>> for i, c in enumerate(s):
...     if not c.isdigit():
...         break
... 
>>> s[:i] + s[i:].capitalize()
'123Sa'

一行代码:' '.join(sub[:1].upper() + sub[1:]用于文本中的sub。分割(' '))

我想到了这个:

import re

regex = re.compile("[A-Za-z]") # find a alpha
str = "1st str"
s = regex.search(str).group() # find the first alpha
str = str.replace(s, s.upper(), 1) # replace only 1 instance
print str

正如Chen Houwu回答的,可以使用字符串包:

import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"