In this tutorial, I am going to capitalize the first letter of all words in a string using different methods. In Python string is Immutable, so when you use any method to manipulate string it will return as a new string.
Method 1
In this method, I will use the .title() function for capitalizing a word’s first letter in a string.
Code
str = 'the one piece is real' result = str.title() print(result)
Method 2
In this method, importing string which is a built-in module in Python is necessary. Python string module has some classes and utility functions for string manipulation. Here I will use the string.capwords() which takes a string as a parameter and capitalizes all the word’s first letters in a string.
Code
import string str = 'the one piece is real' result = string.capwords(str) print(result)
Method 3
In this method, I will be using .capitalize() function. At first, I have to use the .split() function which will split the string from spaces and store it into a list. Then using a for loop we will iterate the list and store it in a variable with the .capitalize() function applied which will capitalize the first letter of a word and adding it with a space. It will give an output that capitalizes all the word’s first letters in the string.
Code
s = 'the one piece is real' result = "" words = s.split() for i in words: result = result + " " + i.capitalize() print(result)
Output
The One Piece Is Real