PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 14, 2022

[FIXED] How to capitalize the First letter of each word in python?

 August 14, 2022     function, output, python, python-3.x, return     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing