Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

I need to capitalize a string in Python, without also converting the rest of the string to lower-case. This seems trivial but I can't seem to find a simple way to do it in Python.

Given a string like this:

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

In Perl I could do this:

ucfirst($string)

which would produce the result I need:

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

Or with Perl's regular expression modifiers I could also do something like this:

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

and that would work ok too:

> 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!
>

But in Python, the str.capitalize() method lower-cases the whole string first:

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

While the title() method upper-cases every word, not just the first one:

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

Is there any simple/one-line way in Python of capitalizing only the first letter of a string without lower-casing the rest of the string?

like image 333
Jeremy Jones Avatar asked May 12 '16 08:05

Jeremy Jones


3 Answers

If what you are interested in is upcasing every first character and lower casing the rest (not exactly what the OP is asking for), this is much cleaner:

string.title()
like image 97
Jazul Kerk Avatar answered Oct 05 '22 13:10

Jazul Kerk


How about:

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

The output is:

I'm Brian, and so's my wife!
like image 22
yktoo Avatar answered Oct 05 '22 12:10

yktoo


Just use string slicing:

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

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

like image 21
Daniel Roseman Avatar answered Oct 05 '22 13:10

Daniel Roseman