Python capitalize the first letter of every word in a string | Example code

Use title() to capitalize the first letter of every word in a string in python. Python Str class provides a member function title() which makes each word title cased in string.

sample_text.title()

It converts the first character of each word to upper case and all remaining characters of the word to lower case.

Example code capitalize the first letter of every word

Python simple code converts the first letter of each word to Upper case and all others to lower case.

sample_text = "Python sample string test"

result = sample_text.title()
print(result)

Output:

Python capitalize the first letter of every word in a string

Using Regular expression

You can also use Regex to capitalize the first letter of each word in a string

import re

s = 'the brown fox'


def repl_func(m):
    """process regular expression match groups for word upper-casing problem"""
    return m.group(1) + m.group(2).upper()


s = re.sub("(^|\s)(\S)", repl_func, s)

print(s)

Output: The Brown Fox

Using string.capwords()

A capwords() function to convert the first letter to uppercase and all other remaining letters to lower case. You have to import the string module to use this function.

import string

sample_text = "Python sample string test"

result = string.capwords(sample_text)
print(result)

.Output: Python Sample String Test

Do comment if you have any doubts and suggestions on this Python capitalize code.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

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