How to downcase the first character of a string?

后端 未结 8 707
醉酒成梦
醉酒成梦 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:32

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

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