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:
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.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.