2012-09-13 175 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(' '))