簡體   English   中英

什么是Perl的ucfirst()或s /// e的Python等價物?

[英]What is the Python equivalent of Perl's ucfirst() or s///e?

我需要在Python中大寫一個字符串,而不是將其余的字符串轉換為小寫字母。 這似乎微不足道,但我似乎無法找到一種簡單的方法在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;
[Control d to exit]
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!"
>>>

雖然title()方法高舉每個單詞,而不僅僅是第一個單詞:

>>> s.title()
"I'M Brian, And So'S My Wife!" 
>>>

在Python中是否有任何簡單/單行的方式只使用字符串的第一個字母而不低於字符串的其余部分?

怎么樣:

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

輸出是:

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

如果您感興趣的是將每個第一個字符升級並將其余部分置於其他部分(不完全是OP所要求的),則更清晰:

string.title()

只需使用字符串切片:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM