Skip to content

Python capitalize each word | Example code

  • by

Use the title() function to capitalize each word in Python. Python’s Str class provides a function title(), it converts the first character of every word of a given string to upper case

Example how to capitalize each word in Python

Simple example code capitalizes the first character of each word in a string.

txt = 'the brOwn Fox'

res = txt.title()

print(res)

Output:

Or

Use capitalize() function with a join() and split() functions. Split into words, initial-cap each word from the split groups, and rejoin.

txt = 'the brOwn Fox'

res = " ".join(w.capitalize() for w in txt.split())

# OR use 

#res = ' '.join(w[0].upper() + w[1:] for w in s.split())


print(res)

Output: The Brown Fox

Using a custom function:

def capitalize_each_word(input_string):
    words = input_string.split()
    capitalized_words = [word.capitalize() for word in words]
    return ' '.join(capitalized_words)

input_string = "hello world"
capitalized_string = capitalize_each_word(input_string)
print(capitalized_string)  # Output: Hello World

In the custom function approach, the split() method is used to split the input string into a list of words. Then, a list comprehension is used to capitalize each word, and finally, the join() method is used to combine the capitalized words back into a single string.

Comment if you have any doubts or suggestions on this Python capitalize topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading