Issue
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.
the code I've tried:
def solve(s):
words = s.split()
flag = False
for word in words:
if isinstance(word[0], str):
flag = True
else:
flag = False
if flag:
return s.title()
else:
# don't know what to do
s = input()
print(solve(s))
this code works fine for most cases except for one,
frustrating testcase: '1 w 2 r 3g', and the output should be '1 W 2 R 3g', but since we are using the .title() method last 'g' will also be capitalized.
Solution
We can try using re.sub
here matching the pattern \b(.)
, along with a callback function which uppercases the single letter being matched.
inp = '1 w 2 r 3g'
output = re.sub(r'\b(.)', lambda x: x.group(1).upper(), inp)
print(output) # 1 W 2 R 3g
Answered By - Tim Biegeleisen Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.