Python 3 – String title() Method
In Python, the title() method is used to convert the first character of each word to uppercase and the remaining characters to lowercase. The title() method is a built-in method of the string class and can be used to convert all string values to title case.
Syntax
str.title()
Example 1
text = "this is a string"
new_text = text.title()
print(new_text)
Output:
This Is A String
In the example above, we define a variable called text
and assign it a string value of “this is a string”. We then use the title() method to convert the string value to title case and assign the new value to new_text
. Finally, we use the print statement to output new_text
.
Example 2
s = "Welcome to Python!"
print(s.title())
Output:
Welcome To Python!
In this example, we define a string variable s
and output its value using the title() method. The first character of each word is capitalized while the rest of the letters are converted to lowercase.
Example 3
s = "python is an amazing programming language"
print(s.title())
Output:
Python Is An Amazing Programming Language
In this example, we define a string variable s
and use the title() method to capitalize the first letter of each word. The method also automatically converts the remainder of the word to lowercase.
Example 4
s = "DREAMS OFTEN BECOME CHALLENGES"
print(s.title())
Output:
Dreams Often Become Challenges
In this example, we define a string variable s
and use the title() method to correct the capitalization of each word.
Conclusion
In conclusion, the title() method is a string method in Python that can be used to convert a string to title case. The first character of each word is converted to uppercase and the remaining characters are converted to lowercase. This method can be helpful in formatting text or in making strings more readable.