2016-05-12 68 views
6

我需要在Python中大寫一個字符串,而不需要將字符串的其餘部分轉換爲小寫。這看起來微不足道,但我似乎無法找到一種簡單的方法來在Python中完成它。什麼是Perl的ucfirst()或s /// e的Python等價物?

給定一個字符串,像這樣:

"i'm Brian, and so's my wife!" 

在Perl我可以這樣做:

ucfirst($string) 

將產生的結果我需要:

I'm Brian, and so's my wife! 

或用Perl的正表達修飾符我也可以做這樣的事情:

$string =~ s/^([a-z])/uc $1/e; 

和,將工作也沒關係:

> perl -l 
$s = "i'm Brian, and so's my wife!"; 
$s =~ s/^([a-z])/uc $1/e; 
print $s; 
[EOF] 
I'm Brian, and so's my wife! 
> 

但是在Python,整串str.capitalize()方法較低的情況下第一:

>>> s = "i'm Brian, and so's my wife!" 
>>> s.capitalize() 
"I'm brian, and so's my wife!" 
>>> 

我沒有看到在Python的re模塊中的任何等同的'e'修飾符,這將允許我使用正則表達式來完成。

是否有任何簡單的/單行的方式來大寫Python中的字符串的第一個字母,而不會降低字符串的其餘部分?

回答

11

如何:

s = "i'm Brian, and so's my wife!" 
print s[0].upper() + s[1:] 

輸出是:

I'm Brian, and so's my wife! 
5

只需使用字符切片:

s[0].upper() + s[1:] 

注意,字符串是不可變的;這個,就像capitalize()一樣,返回一個新的字符串。

10

這是乾淨多了:

string.title() 
+0

這麼好,是最好的,尤其是當有很多不必要的大寫的字符串中的字母 –

+0

太好了。 thx人。 –

相關問題