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 round()
Python Set isdisjoint()
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
JavaScript Eval: run a code string
Python String replace()
Python String count()
Intelligent Projects Using Python - Santanu Pattanayak
Convert String to int or Integer in Java
Python strptime()
Python Object Oriented Programming
Deep Learning with Python - Francois Chollet
Python Numbers, Type Conversion and Mathematics
Python Program to Return Multiple Values From a Function
Python Program to Add Two Matrices
Python Program to Find HCF or GCD
Python Set issubset()
Python Program to Print Hello world!
Java – String to Reader
Python Program to Display Powers of 2 Using Anonymous Function
Python abs()
Python String isalpha()
Python Program to Access Index of a List Using for Loop
Python format()
Most commonly used String methods in Java
Split a String in Java
Python setattr()
Python String join()
Python str()
Python dir()
Python classmethod()
Node.js vs Python for Backend Development
Java InputStream to String