Skip to content

Python capitalize String method | First, all or every Letter example

  • by

Python capitalizes string method is used to converts the first character of a string (first letter of the first word in the sentence) to the capital (uppercase) letter. The string will same if the string has the first character capital.

Python capitalize String method First, all or every Letter example

Syntax

The capitalize() method returns a string where the first letter is upper case. And this method does not take any parameter.

string.capitalize()

Python capitalize the first letter of a sentence

This is a simple example of how to use the capitalize() method in python. The output should be uppercase of the first letter.

txt_str = "hello, and welcome to my world."
x = txt_str.capitalize()

print(x)

Output: Hello, and welcome to my world.

Interview Questions & Answer

Q: How to Python capitalize all letters?

Answer: To change a string into uppercase in use upper() method in python.

txt_str = "hello, and welcome to my world."

x = txt_str.upper()

print(x)

Q: How to Python capitalize the first letter of every word in a string?

Answer: To capitalize the first letter of each word in a string use title() method in python.

txt_str = "hello, and welcome to my world."

x = txt_str.title()

print(x)

Q: What happens if the first character is a number?

Answer: If in a sentence first, character (letter) is is number then nothing will change in a sentence. Try out yourself with Non-alphabetic First Character and do comment.

txt_str = "7 hello, and welcome to my world."

x = txt_str.capitalize()

print(x)
 

Output: 7 hello, and welcome to my world.

Related article: Python uppercase function upper() | convert string to Uppercase

Do comment if you have any doubts and suggestions on the tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Examples of Python capitalize are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *