Skip to content
Advertisement

New to Python: How to keep the first letter of each word capitalized?

I was practicing with this tiny program with the hopes to capitalize the first letter of each word in: john Smith. I wanted to capitalize the j in john so I would have an end result of John Smith and this is the code I used:

name = "john Smith"

if (name[0].islower()):
    name = name.capitalize()
print(name)

Though, capitalizing the first letter caused an output of: John smith where the S was converted to a lowercase. How can I capitalize the letter j without messing with the rest of the name?

I thank you all for your time and future responses! I appreciate it very much!!!

Advertisement

Answer

As @j1-lee pointed out, what you are looking for is the title method, which will capitalize each word (as opposed to capitalize, which will capitalize only the first word, as if it was a sentence).

So your code becomes

name = "john smith"
name = name.title()
print(name) #> John Smith
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement