What is the Python Perl equivalent of ucfirst () or s /// e?

I need to use a header string in Python, and also not convert the rest of the string to lowercase. This seems trivial, but I cannot find an easy way to do this in Python.

Given a line like this:

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

In Perl, I could do this:

 ucfirst($string) 

which will give the result I need:

 I'm Brian, and so my wife! 

Or with Perl regex modifiers, I could do something like this:

 $string =~ s/^([az])/uc $1/e; 

and this will work fine too:

 > perl -l $s = "i'm Brian, and so my wife!"; $s =~ s/^([az])/uc $1/e; print $s; [Control d to exit] I'm Brian, and so my wife! > 

But in Python, the str.capitalize () method is first lowercase in the first place:

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

While the title () method prescribes every word, not just the first:

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

Is there any simple / single line way in Python to use only the first letter of a string without lowercase the rest of the string?

+10
source share
3 answers

What about:

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

Output:

 I'm Brian, and so my wife! 
+16
source

If what interests you is to wrap around every first character, and the bottom one around the rest (not exactly what the OP asks for), it's a lot cleaner:

 string.title() 
+13
source

Just use line slicing:

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

Note that strings are immutable; this, like capitalize() , returns a new line.

+7
source

All Articles