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.
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)
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
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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.