Split the text into words, change the first letter of each word to a capital, and join the words again. The rest of each word is not changed.
The program
text = input("Enter a sentence: ") new_words = [] for word in text.split(): new_words.append(word[0].upper() + word[1:]) print(" ".join(new_words))
Typed in this example: the NASA team met in london. Press Run to type your own.
Enter a sentence: the NASA team met in london The NASA Team Met In London
How it works
text.split()gives a list of words.split()never returns an empty word, soword[0]is always safe.word[0].upper()is the first letter as a capital.word[1:]is the rest of the word, unchanged." ".join(new_words)puts the words back together with one space between them. Extra spaces in the input are not kept.
Compare with capitalize() and title()
Python has two methods that look similar, but both make every other letter small:
text = "the NASA team met in london" print(" ".join(word.capitalize() for word in text.split())) print(text.title())
The Nasa Team Met In London The Nasa Team Met In London
"NASA" becomes "Nasa" in both. Use capitalize() or title() when the input is all small letters, or when you want the rest of each word in small letters. Use the program above when some words, such as names and short forms, already have capitals that must stay. The title case page shows one more difference between title() and string.capwords().