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()
CodePudding user response:
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
CodePudding user response:
Try a simple loop that capitalizes a character if preceded by a space.
x = re.sub("[^A-Za-z0-9]", " ", s)
a = x[0]
for i in range(1, len(x)):
if x[i - 1] == " ":
a = a x[i].title()
else:
a = a x[i]
return a
Output is:
1 W 2 R 3g
CodePudding user response:
Can’t you just str.title()
this? There is no such thing as an uppercase number, so ”123abc”.title()
should produce your desired result still.