Skip to main content

How to capitalize the first letter of each word in a string in Python

How to capitalize the first letter of each word in a string in Python.

Here's a step-by-step tutorial on how to capitalize the first letter of each word in a string in Python:

  1. Start by defining a function that will perform the capitalization. Let's call it capitalize_words.
def capitalize_words(string):
# Code to be added here
pass
  1. Next, split the string into a list of words using the split() method. This will separate the string at each space character and create a list of words.
def capitalize_words(string):
words = string.split()
pass
  1. Iterate through each word in the words list using a loop. We will use a for loop for this.
def capitalize_words(string):
words = string.split()
for word in words:
pass
  1. Inside the loop, capitalize the first letter of each word using the capitalize() method. This method converts the first character of a string to uppercase and leaves the rest of the string unchanged.
def capitalize_words(string):
words = string.split()
for word in words:
capitalized_word = word.capitalize()
pass
  1. Replace the original word in the words list with the capitalized word using the index() method. This method returns the index of the first occurrence of a specified value in a list.
def capitalize_words(string):
words = string.split()
for word in words:
capitalized_word = word.capitalize()
index = words.index(word)
words[index] = capitalized_word
  1. Finally, join the capitalized words back into a single string using the join() method. This method concatenates all items in a list into a single string, using a specified delimiter (in this case, a space character).
def capitalize_words(string):
words = string.split()
for word in words:
capitalized_word = word.capitalize()
index = words.index(word)
words[index] = capitalized_word
capitalized_string = ' '.join(words)
return capitalized_string

That's it! You can now use the capitalize_words function to capitalize the first letter of each word in a given string. Here's an example usage:

string = "hello world"
capitalized_string = capitalize_words(string)
print(capitalized_string)

Output:

Hello World

Feel free to modify the function according to your specific requirements.