'How to capitalize the First letter of each word 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.

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 1:[1]

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

Solution 2:[2]

#replace

def solve(s):

for i in s.split():
    s = s.replace(i,i.capitalize())
return s

In Python, the capitalize() method returns a copy of the original string and converts the first character of the string to a capital (uppercase) letter while making all other characters in the string lowercase letters.

Solution 3:[3]

name = 'robert lewandowski'
print(name.title())

Output -

Robert Lewandowski

Solution 4:[4]

Check this if solves your problem

z=[]
s = input()
x=s.split(" ")
print(x)
for i in x:
    z.append(i.capitalize())

v=" ".join(z)
print(v)

Solution 5:[5]

if you use numpy module , then easily you can achieve the answer! for example = Alison Heck

from numpy import *

answer=input("give your input").title()
print(answer)

this module especially made for this purpose.

Solution 6:[6]

You can call like:

s = '1 w 2 r 3gH'
print(' '.join([word.capitalize() for word in s.split()]))
# 1 W 2 R 3gh

But note that the remaining letters also will be made in lowercase except the first letter as given in the altered example.

Solution 7:[7]

You can use RE or you can try a solution like this

def solve(s):
    res=""
    for i in range(len(s)):
        if i==0:
           if s[i].isalpha():
               res+=s[i].capitalize()
           else:
               res+=s[i]
        else:
            if s[i].isalpha() and s[i-1]==' ':
                res+=s[i].capitalize()
            else:
                res+=s[i]
    return res 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tim Biegeleisen
Solution 2 arango_86
Solution 3 Zero
Solution 4 Vivs
Solution 5 Nikhil Mehta
Solution 6
Solution 7 Mahmoud Maghrabi