0

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()

3 Answers3

3

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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
2

One option is to use a regex and limit it to 1 replacement, eg:

>>> import re
>>> re.sub('[a-zA-Z]', lambda m: m.group().upper(), '2cat', 1)
'2Cat'
>>> re.sub('[a-zA-Z]', lambda m: m.group().upper(), 'sun', 1)
'Sun'
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

You only seem to have either a word starting with a letter or where the second character is a letter so you just have two possibilities:

print(s.capitalize() if s[0].isalpha() else s[0] +  s[1:].capitalize())
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321