我知道.capitalize()将字符串的第一个字母大写,但如果第一个字符是整数怎么办?
this
1bob
5sandy
这个
1Bob
5Sandy
我知道.capitalize()将字符串的第一个字母大写,但如果第一个字符是整数怎么办?
this
1bob
5sandy
这个
1Bob
5Sandy
当前回答
一行代码:' '.join(sub[:1].upper() + sub[1:]用于文本中的sub。分割(' '))
其他回答
你可以使用regex替换每个单词的第一个字母(前面有一个数字):
re.sub(r'(\d\w)', lambda w: w.group().upper(), '1bob 5sandy')
output:
1Bob 5Sandy
只是因为没人提过
>>> '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'中是这样。
正如Chen Houwu回答的,可以使用字符串包:
import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"
def solve(s):
names = list(s.split(" "))
return " ".join([i.capitalize() for i in names])
输入你的名字,无名氏
返回首字母大写。(如果第一个字符是数字,则不大写)
适用于任何名称长度
我想到了这个:
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