【发布时间】:2016-05-12 08:18:46
【问题描述】:
我需要在 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 中是否有任何简单/单行的方法可以只大写字符串的第一个字母而不小写字符串的其余部分?
【问题讨论】: