pythonpython-3.xstringpython-recapitalize

Capitalize First Letter but not when number comes in first place in Python


You are asked to ensure that the first and last names of people begin > with a capital letter in their passports. For example, alison heck > should be capitalised correctly as Alison Heck. NOTE In a word only the first character is capitalized. Example 12abc when capitalized remains 12abc.

One test case is failed i.e. Input (stdin)

1 w 2 r 3g

Expected Output

1 W 2 R 3g

My Output

1 W 2 R 3G

Please improve this code

import math
import os
import random
import re
import sys


def solve(s):
    
    
    x = re.sub("[^A-Za-z0-9]", " ", s)
    a = x.title()
    return a

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()

    result = solve(s)

    fptr.write(result + '\n')

    fptr.close()

Solution

  • You could split the input on space and then use capitalize, which will convert the first character of each string to titlecase. Then you can join the words together again. For example:

    inp = '1 w 2 r 3g'
    res = ' '.join(s.capitalize() for s in inp.split())
    

    Output:

    1 W 2 R 3g