【问题标题】:What is the Python equivalent of Perl's ucfirst() or s///e?Perl 的 ucfirst() 或 s///e 的 Python 等价物是什么?
【发布时间】: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 中是否有任何简单/单行的方法可以只大写字符串的第一个字母而不小写字符串的其余部分?

【问题讨论】:

    标签: python string


    【解决方案1】:

    如果您感兴趣的是将 每个 第一个字符大写,其余部分小写(不完全是 OP 所要求的),那么这会更简洁:

    string.title()
    

    【讨论】:

    • 太好了,最好的,尤其是当字符串中有很多不必要的大写字母时
    • -1 Perl 的ucfirsttitle 的工作方式非常不同:ucfirst 仅作用于字符串的第一个字母,而 Python 的 title 将所有单词大写并将其他字母转换为小写案子。所以"i'm Brian, and so's my wife!".title() 将导致"I'M Brian, And So'S My Wife!" 这与Perl 中ucfirst 的结果完全不同:"I'm Brian, and so's my wife!"
    【解决方案2】:

    怎么样:

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

    输出是:

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

    【讨论】:

    • 在 Perl 中,ucfirst-ing 一个未定义的值并不是致命的,所以要使用它,你应该使用 trycatch 它,但无论如何这都是正常的。 :-)
    • 这不是 Python 的方式 :(
    【解决方案3】:

    只需使用字符串切片:

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

    注意字符串是不可变的;这和capitalize() 一样,返回一个新字符串。

    【讨论】:

      猜你喜欢
      • 2016-06-12
      • 2012-03-20
      • 2022-10-17
      • 2011-02-02
      • 2011-03-25
      • 2023-04-04
      • 1970-01-01
      • 2014-05-31
      • 1970-01-01
      相关资源
      最近更新 更多