2012-09-13 181 views

回答

164

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

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

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

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

我问如何大写第一个字母字符 – user1442957

+5

,这是这个答案做什么,几乎 – njzk2

+12

我会用,如果c.isalpha(),而不是如果不是c。 isdigit() – njzk2

0

我想出了这一点:

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 
+0

如果没有alpha,则不起作用 –

174

只是因为没有其他人提到它:

>>> 'bob'.title() 
'Bob' 
>>> 'sandy'.title() 
'Sandy' 
>>> '1bob'.title() 
'1Bob' 
>>> '1sandy'.title() 
'1Sandy' 

然而,这也给

>>> '1bob sandy'.title() 
'1Bob Sandy' 
>>> '1JoeBob'.title() 
'1Joebob' 

即它不会仅仅利用第一个alphabeti c字符。但后来.capitalize()有同样的问题,至少在那'joe Bob'.capitalize() == 'Joe bob',所以呢。

9

这里是一个班轮,将首字母大写为,并留下所有后续字母的大小写:

import re 

key = 'wordsWithOtherUppercaseLetters' 
key = re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), key, 1) 
print key 

这将导致WordsWithOtherUppercaseLetters

29

这类似于在@匿名的回答它保持字符串的其余部分完好无损,而不需要re模块。

def upperfirst(x): 
    return x[0].upper() + x[1:] 

x = 'thisIsCamelCase' 

y = upperfirst(x) 

print(y) 

# Result: 'ThisIsCamelCase' # 

由于@Xan指出,该功能可以使用更多的错误检查(如检查到x是一个序列 - 然而我忽略的边缘情况来说明该技术)

+2

非常有用,但需要'len(x)== 0'分支。 – Xan

+0

因为python 2.5空壳仍然可以在一行上处理: 'return x [0] .upper()+ x [1:] if len(x)> 0 else x' – danio

+0

非常有用的答案,因为'capitalize '&'title'首先小写整个字符串,然后大写只有第一个字母。 –

0

,可随时更换使用正则表达式每个单词的第一个字母(preceded by a digit):

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

output: 
1Bob 5Sandy 
0

如同看见here由陈吼吴回答,有可能使用字符串包:

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

一个班轮:' '.join(token_text[:1].upper() + token_text[1:] for sub in text.split(' '))