我知道 .capitalize() 可以将字符串的第一个字母大写,但如果第一个字符是整数会怎么样呢?
this
1bob
5sandy
到这个
1Bob
5Sandy
我知道 .capitalize() 可以将字符串的第一个字母大写,但如果第一个字符是整数会怎么样呢?
this
1bob
5sandy
到这个
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'
,所以无所谓了。
如果第一个字符是整数,则不会将第一个字母大写。
>>> '2s'.capitalize()
'2s'
如果你想要这个功能,去掉数字后,你可以使用 '2'.isdigit()
检查每个字符。>>> s = '123sa'
>>> for i, c in enumerate(s):
... if not c.isdigit():
... break
...
>>> s[:i] + s[i:].capitalize()
'123Sa'
这与@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指出我没有回答问题!-已修复
len(x) == 0
分支。 - Xanreturn x[0].upper() + x[1:] if len(x) > 0 else x
- daniocapitalize
和 title
首先将整个字符串变为小写,然后只将第一个字母大写。 - Jonas Libbrechta[:1].upper() + a[1:]
,这将解决len(X)==0
的特殊情况。 - normanius这里有一个一行代码,它会将第一个字母大写并保留所有后续字母的大小写:
import re
key = 'wordsWithOtherUppercaseLetters'
key = re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), key, 1)
print key
这将导致WordsWithOtherUppercaseLetters
如此处由Chen Houwu回答,可以使用字符串包:
import string
string.capwords("they're bill's friends from the UK")
>>>"They're Bill's Friends From The Uk"
' '.join(sub[:1].upper() + sub[1:] for sub in text.split(' '))
。该代码可将给定文本中所有单词首字母大写,并用空格连接它们。请注意,保留了代码中的HTML标记。紧跟着数字
)。re.sub(r'(\d\w)', lambda w: w.group().upper(), '1bob 5sandy')
output:
1Bob 5Sandy
def solve(s):
for i in s[:].split():
s = s.replace(i, i.capitalize())
return s
这是实际工作的代码。.title()在'12name'情况下无法正常工作。
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
def solve(s):
names = list(s.split(" "))
return " ".join([i.capitalize() for i in names])
next((i for i,e in enumerate(test) if not e.isdigit()), '0')
可以解决空字符串的问题。 - njzk2.capitalize
方法也会将其他字符转换为小写字母。根据官方文档:“返回S的标题大小写版本,即单词以大写字母开头,所有剩余大小写字母均为小写”。 - karantan