Search code examples
pythoncapitalizeletter

python capitalize first letter only


I am aware .capitalize() capitalizes the first letter of a string but what if the first character is a integer?

this

1bob
5sandy

to this

1Bob
5Sandy

Solution

  • If the first character is an integer, it will not capitalize the first letter.

    >>> '2s'.capitalize()
    '2s'
    

    If you want the functionality, strip off the digits, you can use '2'.isdigit() to check for each character.

    >>> s = '123sa'
    >>> for i, c in enumerate(s):
    ...     if not c.isdigit():
    ...         break
    ... 
    >>> s[:i] + s[i:].capitalize()
    '123Sa'