我知道.capitalize()将字符串的第一个字母大写,但如果第一个字符是整数怎么办?
this
1bob
5sandy
这个
1Bob
5Sandy
我知道.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指出我没有回答这个问题!固定,
其他回答
def solve(s):
for i in s[:].split():
s = s.replace(i, i.capitalize())
return s
这是work. .title()在'12name'情况下不工作的实际代码
只是因为没人提过
>>> 'bob'.title()
'Bob'
>>> 'sandy'.title()
'Sandy'
>>> '1bob'.title()
'1Bob'
>>> '1sandy'.title()
'1Sandy'
然而,这也会
>>> '1bob sandy'.title()
'1Bob Sandy'
>>> '1JoeBob'.title()
'1Joebob'
也就是说,它不仅仅是首字母大写。但是。capitalize()也有同样的问题,至少在'joe Bob'.capitalize() == 'joe Bob'中是这样。
这与@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指出我没有回答这个问题!固定,
我想到了这个:
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
下面是一个一行程序,它将第一个字母大写,并保留所有后续字母的大小写:
import re
key = 'wordsWithOtherUppercaseLetters'
key = re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), key, 1)
print key
这将导致WordsWithOtherUppercaseLetters