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 Convert Decimal to Binary Using Recursion
Python Set intersection_update()
Python List copy()
Python Set union()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Converting a Stack Trace to a String in Java
Python time Module
Python String isupper()
Python Program to Convert String to Datetime
Python Exception Handling Using try, except and finally statement
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python List Comprehension
Python Namespace and Scope
Python Program to Compute the Power of a Number
Python Program to Find Sum of Natural Numbers Using Recursion
Python Closures
Python Dictionary items()
Python String lstrip()
Python bytes()
Python next()
Python Matrices and NumPy Arrays
Python datetime
Python List insert()
JavaScript Methods of RegExp and String
Python String maketrans()
Java Program to Permute All Letters of an Input String
Python Recursion
Python Program to Print Colored Text to the Terminal
Python Custom Exceptions
Python dir()
Python String rindex()
Python Anonymous / Lambda Function