How to Capitalize a String in Python
To capitalize a string in Python, you can use the capitalize(), upper(), or title() functions.
The following examples show how to capitalize a string in Python.
Using capitalize() Function
We can use the capitalize() function to capitalize the first character of a string.
Suppose we have the following string:
# Declare string
str1 = "hello, world"
# Print original string
print("Original string:", str1)
# Capitalize string
capitalized_str = str1.capitalize()
# Show updated string
print("Updated string:", capitalized_str)
Output: 👇️
Original string: hello, world
Updated string: Hello, world
In this example, we use the capitalize() function to capitalize the first character of str1.
Using upper() Function
We can use the upper() function to convert all characters of a string to uppercase.
Suppose we have the following string:
# Declare string
str1 = "hello, world"
# Print original string
print("Original string:", str1)
# Capitalize string
upper_str = str1.upper()
# Show updated string
print("Updated string:", upper_str)
Output: 👇️
Original string: hello, world
Updated string: HELLO, WORLD
In this example, we use the upper() function to convert all characters of str1 to uppercase.
Using title() Function
We can use the title() function to capitalize the first character of each word in a string.
Suppose we have the following string:
# Declare string
str2 = "the quick brown fox jumps over the lazy dog"
# Print original string
print("Original string:", str2)
# Capitalize string
title_str = str2.title()
# Show updated string
print("Updated string:", title_str)
Output: 👇️
Original string: the quick brown fox jumps over the lazy dog
Updated string: The Quick Brown Fox Jumps Over The Lazy Dog
In this example, we use the title() function to capitalize the first character of each word in str2.