How to downcase the first character of a string?

后端 未结 8 706
醉酒成梦
醉酒成梦 2020-12-08 12:44

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 P

相关标签:
8条回答
  • 2020-12-08 13:12

    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.

    0 讨论(0)
  • 2020-12-08 13:13
    s = "Bobby tables"
    s = s[0].lower() + s[1:]
    
    0 讨论(0)
  • 2020-12-08 13:21
    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  :-)
    
    0 讨论(0)
  • 2020-12-08 13:26

    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
    
    0 讨论(0)
  • 2020-12-08 13:26

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

    def uncapitalize(s):
        return s[:1].lower() + s[1:].upper()
    
    0 讨论(0)
  • 2020-12-08 13:26

    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']
    
    0 讨论(0)
提交回复
热议问题