87

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?

1
  • 4
    Are you sure s.lower() is not what you want? Otherwise you could get weird results such as 'hELLO'. Oct 1, 2010 at 16:57

9 Answers 9

87

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'
8
  • I find lambdas to be much less readable than a regular function definition. Do you really think it's worth it just to save a single line? Jan 5, 2022 at 5:07
  • @MarkRansom: Quite the contrary, I find this very readable. YMMV.
    – martineau
    Jan 5, 2022 at 5:10
  • Yes I'll grant you that YMMV. But since I'm in a complainy mood, does it bother you that this function returns an empty string for any falsey input even if it isn't a string? For example 0 or [] or False. Jan 5, 2022 at 5:18
  • 1
    @serv-inc not at all clear on what you're trying to tell me. Feb 16, 2022 at 17:33
  • 1
    @serv-inc I wouldn't consider that an improvement. Thanks for trying though. Feb 17, 2022 at 13:07
47
s = "Bobby tables"
s = s[0].lower() + s[1:]
2
  • Is there a way this can be edited to lowercase more than just the first letter? I thought I could do something like 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
  • 1
    @christylynn002: you need to use slicing. s = s[:11].lower() + s[11:]
    – maedox
    Feb 29, 2016 at 9:58
22
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  :-)
12
  • 4
    your original answer was perfect, but len(s) == 0 is just bizzare. Oct 1, 2010 at 15:57
  • 4
    @SilentGhost: It's one of a million valid ways to say what it's saying. It's related to the problem that it's there to solve - you mustn't run the code if the string is zero length, so that's explicitly what I'm testing for. I could have said if not s: but that doesn't represent the problem quite so well. Oct 1, 2010 at 16:00
  • 7
    @SilentGhost: None of us knows how experienced the OP is. It's easy to miss corner cases when someone provides you with code that demonstrably works. I'd rather err on the side of caution than provide an answer that I know will fail in a common case. Oct 1, 2010 at 16:33
  • 4
    Thorough answers like these tend to educate the asker better than concise ones. Given that the asker is asking this, it is reasonable to point out the corner case. It is an extra tidbit of knowledge that the asker can take away from the answer and keep in mind when he's making similar functions in the future.
    – JoshD
    Oct 1, 2010 at 16:52
  • 5
    @RichieHindle: The test for zero length strings can be omitted if one uses slicing: 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
10

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
2
  • I don't think it's the intention of the OP Oct 1, 2010 at 17:32
  • 2
    @Xavier: You're probably right, but it's interesting that capitalize mucks with the rest of the string. Oct 1, 2010 at 22:04
8

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("")
>>> 
2
  • Aye. I'd also like to know why this was down voted. If there is a mistake I'll be the first to want to know. Oct 1, 2010 at 17:08
  • 4
    There is a mistake - if you pass in an empty string you get None back, since you have an empty return statement. That is unintuitive and bound to lead to bugs in the calling code.
    – Dave Kirby
    Oct 2, 2010 at 20:24
7

No need to handle special cases (and I think the symmetry is more Pythonic):

def uncapitalize(s):
    return s[:1].lower() + s[1:].upper()
3
  • 9
    There shouldn't be .upper() in your function. May 13, 2015 at 15:49
  • 2
    It's prone to error, check length of s before performing operation Dec 28, 2016 at 8:29
  • 3
    @harshil9968 one of the really nice things about slices in Python is that they work even when the indexes are out of bounds. You might get an empty string, but it still works. Jan 5, 2022 at 5:10
0

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.

2
  • how will it raise an exception that the other solutions wouldn't? The first opportunity for an error is when you slice and all of the other ones do that anyways. Oct 2, 2010 at 6:08
  • Not so - the accepted answer, for instance, doesn't raise an exception if you pass it an empty list. Oct 2, 2010 at 9:19
0

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']
1
  • You don't even need to use enumerate in that case: l = [x[0].lower() + x[1:] for x in list(l)]
    – Natim
    Nov 14, 2017 at 9:32
0

pip install pydash first.

import pydash  # pip install pydash

assert pydash.lower_first("WriteLine") == "writeLine"

https://github.com/dgilland/pydash

https://pydash.readthedocs.io/en/latest/

https://pypi.org/project/pydash/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.