Search code examples
pythonpython-3.xuppercasecapitalize

python function capitalize first letter only


I need build a function to transform 1st character only, from any word but also this function need address the problem if the 1st character from the word doesn't starts with a character, for example '_sun',' -tree', '2cat' these words need be like _Sun, -Tree, 2Cat. This is what I have so far, it can convert any word but I don't know how do 2nd part, need use ASCII?? to get value of 1st character and see if the word starts with character?

def convert(capital):
    return capital[0].upper() + capital[1:]

def main():
   print(convert('sun'))

main()

Solution

  • Your function capitalises the first character, regardless.

    For this task, you'll have to find the first character in a different way; you could use str.isalpha() function:

    def convert(capital):
        index = 0
        while index < len(capital) and not capital[index].isalpha():
            index += 1
        return capital[:index] + capital[index:].capitalize()
    

    Another approach would be to use a regular expression-based substitution; you'll have to use a function to uppercase the character found:

    import re
    
    def convert(capital):
        return re.sub(r'([a-z])(.*)$', lambda m: m.group(1).upper() + m.group(2),
                      capital, flags=re.I)
    

    This matches case-insensitively on the first letter, and replaces that with the uppercase version.

    A third idea is to use str.title(), which does the same for all words in a text, but only apply it to the first word:

    def convert(capital):
        first, _, rest = capital.partition(' ')
        return '{} {}'.format(first.title(), rest)