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?
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()
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!
Just use string slicing:
s[0].upper() + s[1:]
Note that strings are immutable; this, just like capitalize()
, returns a new string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With