In Python, we can capitalize the first letter of every word in a string easily with the help of slicing, Python split() function, and the Python upper() function.
string = "this is a string with some words"
def capitalizeFirstLetter(string):
new_strings = []
for x in string.split(" "):
new_strings.append(x[0].upper() + x[1:])
return " ".join(new_strings)
print(capitalizeFirstLetter(string))
#Output:
This Is A String With Some Words
When using string variables in Python, we can easily perform string manipulation to change the value of the string variables.
One such manipulation is to capitalize the first letter of every word in a string.
We can easily capitalize the first letter of every word in Python.
First, we can use the split() function to split the string by spaces to get a list of the words of the string variable. Then, we can loop over each word, and use slicing to get the first character of the string to capitalize with upper() and concatenate that back to the rest of the word.
At the end, we can join the list of capitalized words back together with the join() function.
Below is an example Python function of how you can capitalize the first letter of each word in a string variable.
string = "this is a string with some words"
def capitalizeFirstLetter(string):
new_strings = []
for x in string.split(" "):
new_strings.append(x[0].upper() + x[1:])
return " ".join(new_strings)
print(capitalizeFirstLetter(string))
#Output:
This Is A String With Some Words
How to Make the First Letter of Each Word Lowercase in Python
If you want to go the other way and make the first letter of each word in a string variable lowercase, we can make a small adjustment to our function.
Instead of using the Python upper() function, we can use the lower() function.
Below is an example Python function of how you can make the first letter of each word lowercase.
string = "THIS IS A STRING OF SOME WORDS"
def lowercaseFirstLetter(string):
new_strings = []
for x in string.split(" "):
new_strings.append(x[0].lower() + x[1:])
return " ".join(new_strings)
print(lowercaseFirstLetter(string))
#Output:
tHIS iS a sTRING oF sOME wORDS
Hopefully this article has been useful for you to learn how to capitalize the first letter of each word in Python.