There is a function to capitalize a string, I would like to be able to change the first character of a string to be sure it will be lowercase.
How can I do that in Python?
There is a function to capitalize a string, I would like to be able to change the first character of a string to be sure it will be lowercase.
How can I do that in Python?
One-liner which handles empty strings and None
:
func = lambda s: s[:1].lower() + s[1:] if s else ''
>>> func(None)
>>> ''
>>> func('')
>>> ''
>>> func('MARTINEAU')
>>> 'mARTINEAU'
0
or []
or False
.
Jan 5, 2022 at 5:18
s = "Bobby tables"
s = s[0].lower() + s[1:]
s = s[10].lower() + s[11:]
but this still only gave me the first letter lowercased instead of the first 10.
Jan 8, 2016 at 15:06
def first_lower(s):
if len(s) == 0:
return s
else:
return s[0].lower() + s[1:]
print first_lower("HELLO") # Prints "hELLO"
print first_lower("") # Doesn't crash :-)
len(s) == 0
is just bizzare.
Oct 1, 2010 at 15:57
if not s:
but that doesn't represent the problem quite so well.
Oct 1, 2010 at 16:00
s[:1].lower() + s[1:]
also works for empty strings. I agree that there is no need to handle None.
Oct 2, 2010 at 0:16
Interestingly, none of these answers does exactly the opposite of capitalize()
. For example, capitalize('abC')
returns Abc
rather than AbC
. If you want the opposite of capitalize()
, you need something like:
def uncapitalize(s):
if len(s) > 0:
s = s[0].lower() + s[1:].upper()
return s
capitalize
mucks with the rest of the string.
Oct 1, 2010 at 22:04
Simplest way:
>>> mystring = 'ABCDE'
>>> mystring[0].lower() + mystring[1:]
'aBCDE'
>>>
Update
See this answer (by @RichieHindle) for a more foolproof solution, including handling empty strings. That answer doesn't handle None
though, so here is my take:
>>> def first_lower(s):
if not s: # Added to handle case where s == None
return
else:
return s[0].lower() + s[1:]
>>> first_lower(None)
>>> first_lower("HELLO")
'hELLO'
>>> first_lower("")
>>>
No need to handle special cases (and I think the symmetry is more Pythonic):
def uncapitalize(s):
return s[:1].lower() + s[1:].upper()
I'd write it this way:
def first_lower(s):
if s == "":
return s
return s[0].lower() + s[1:]
This has the (relative) merit that it will throw an error if you inadvertently pass it something that isn't a string, like None
or an empty list.
This duplicate post lead me here.
If you've a list of strings like the one shown below
l = ['SentMessage', 'DeliverySucceeded', 'DeliveryFailed']
Then, to convert the first letter of all items in the list, you can use
l = [x[0].lower() + x[1:] for x in l]
Output
['sentMessage', 'deliverySucceeded', 'deliveryFailed']
l = [x[0].lower() + x[1:] for x in list(l)]
pip install pydash
first.
import pydash # pip install pydash
assert pydash.lower_first("WriteLine") == "writeLine"
https://github.com/dgilland/pydash