Table of Contents
The title() method returns a string with first letter of each word capitalized; a title cased string.
The syntax of title() is:
str.title()
1. title() Parameters
title() method doesn’t take any parameters.
2. Return Value from title()
title() method returns a title cased version of the string. Meaning, the first character of each word is capitalized (if the first character is a letter).
3. Example 1: How Python title() works?
text = 'My favorite number is 25.' print(text.title()) text = '234 k3l2 *43 fun' print(text.title())
Output
My Favorite Number Is 25. 234 K3L2 *43 Fun
4. Example 2: title() with apostrophes
text = "He's an engineer, isn't he?" print(text.title())
Output
He'S An Engineer, Isn'T He?
title() capitalizes the first letter after apostrophes as well.
To solve this issue, you can use regex as follows:
5. Example 3: Using Regex to Title Case String
import re
def titlecase(s):
return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
lambda mo: mo.group(0)[0].upper() +
mo.group(0)[1:].lower(),
s)
text = "He's an engineer, isn't he?"
print(titlecase(text))
Output
He's An Engineer, Isn't He?
Related posts:
Python Program to Check if a Number is Positive, Negative or 0
Python Data Structures and Algorithms - Benjamin Baka
Python Program to Capitalize the First Character of a String
Python Program to Slice Lists
Python String capitalize()
Python iter()
Python hash()
Python Dictionary get()
Python Operators
Python Program to Differentiate Between type() and isinstance()
Python next()
Python chr()
Java – Reader to String
Converting a List to String in Java
Python List append()
Deep Learning with Python - Francois Chollet
Python String istitle()
Python property()
Python input()
Python Program to Check Leap Year
Python Program to Find Hash of File
Python Package
Python Program to Find HCF or GCD
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Program to Trim Whitespace From a String
Python Program to Get the Last Element of the List
Python filter()
Python Directory and Files Management
Python Program to Copy a File
Python timestamp to datetime and vice-versa
Python reversed()
Python Dictionary setdefault()