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 Inheritance
Python String center()
Python String translate()
Python Program Read a File Line by Line Into a List
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Java String Conversions
Python locals()
Python Dictionary setdefault()
How to Get Started With Python?
Python if...else Statement
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Program to Find the Factorial of a Number
Python chr()
APIs in Node.js vs Python - A Comparison
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python String istitle()
Python Program to Check Leap Year
Python dict()
Python Variables, Constants and Literals
Python String swapcase()
Python vars()
Python issubclass()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Program to Get the Class Name of an Instance
Python Program to Generate a Random Number
Python Program to Extract Extension From the File Name
Python tuple()
Python Data Types
Python filter()
Python range()
Python enumerate()