Skip to content

Python capitalize each word | Example code

  • by

Use 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

Do 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

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.