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 Print Output Without a Newline
Python enumerate()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python File I/O Operation
Python Program to Capitalize the First Character of a String
Python Set symmetric_difference_update()
Introduction to Scientific Programming with Python - Joakim Sundnes
Python List count()
Python Program to Find the Factorial of a Number
Python Deep Learning Cookbook - Indra den Bakker
Python Set clear()
Python Tuple
Python map()
Python Data Structures and Algorithms - Benjamin Baka
Python Set issuperset()
Python Function Arguments
Python Program to Get the File Name From the File Path
Python Program to Randomly Select an Element From the List
Python Program to Count the Number of Each Vowel
Python Dictionary items()
Reading an HTTP Response Body as a String in Java
Python Set add()
Python List sort()
Python Custom Exceptions
Python String isdecimal()
Why String is Immutable in Java?
Python filter()
Python del Statement
Python Program to Check Prime Number
Python String format_map()
Python Program to Check the File Size
Python datetime