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 Iterators
Python String rsplit()
Python Program to Make a Flattened List from Nested List
Python Modules
Python Program to Merge Two Dictionaries
Python Tuple
Python iter()
Python Program to Convert Kilometers to Miles
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
String Processing with Apache Commons Lang 3
Java InputStream to String
Python timestamp to datetime and vice-versa
Python String isspace()
Python Program to Get a Substring of a String
Python slice()
Python exec()
Python Strings
Python hex()
Python Program to Display Fibonacci Sequence Using Recursion
Python Program to Differentiate Between del, remove, and pop on a List
Python Program to Find Hash of File
Python Program to Check Whether a String is Palindrome or Not
Python dict()
CharSequence vs. String in Java
Python String isdecimal()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Case-Insensitive String Matching in Java
Python tuple()
Python Input, Output and Import
Python Program to Find Factorial of Number Using Recursion
Python Program to Iterate Over Dictionaries Using for Loop
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda