How to Capitalize First Character of String in Python?

Python – Capitalize First Character of String

To capitalize first character of a String in Python, i.e., transform the first character to upper case, you can use String.capitalize() function.

Call capitalize() method on given string. The method returns a new string where the first character in the original string is transformed to upper case.

Examples

In the following examples, we shall learn how to capitalize a given string. We shall cover different use cases like when the given string starts with a lower case, or an upper case, or a digit.

1. Capitalize given Python string when first character is a lowercase

In the following program, the first character of given String is lower case alphabet. We shall use String.capitalize() function to capitalize the first character.

Python Program

# Given string
x = 'hello world'

# Capitalize string
x_cap = x.capitalize()

print(f"Original String    : {x}")
print(f"Capitalized String : {x_cap}")
Run Code Copy

Output

Original String    : hello world
Capitalized String : Hello world

2. Capitalise given string when first character is an uppercase

If the first character is upper case alphabet, then applying String.capitalize() would not make any change in the resulting string.

Python Program

# Given string
x = 'Hello World'

# Capitalize string
x_cap = x.capitalize()

print(f"Original String    : {x}")
print(f"Capitalized String : {x_cap}")
Run Code Copy

Output

Original String    : Hello World
Capitalized String : Hello world

3. Capitalise given string when first character is a numeric digit

capitalize() function converts only lower case alphabets to upper case. So, it does not affect the given string, if the first character is a numeric digit.

Python Program

# Given string
x = '123 hello world'

# Capitalize string
x_cap = x.capitalize()

print(f"Original String    : {x}")
print(f"Capitalized String : {x_cap}")
Run Code Copy

Output

Original String    : 123 hello world
Capitalized String : 123 hello world

The same explanation holds if the first character is a space, a special symbol, etc.

Summary

In this tutorial of Python Examples, we learned how to capitalise a given string in Python language with the help of well detailed example programs.

Related Tutorials

Code copied to clipboard successfully 👍