Python String title() Method
The Python title() method returns a "titled" string, which means that the first letter of all words is converted to uppercase and the rest of the letters are lowercase.
Python String title() Syntax
The syntax of the title() method.
str.title();
Python String title() Parameters
- None.
Python String title() Return Value
Returns a "titled" string, meaning that all words are converted to uppercase for the first letter.
Python String title() Example#1
The following example demonstrates the use of the title() function.
#!/usr/bin/python3
str = "this is string example from apidemos.com"
print (str.title())
Output:
Python String title() Example#2
The first letter after a non-letter will be converted to an uppercase letter.
#!/usr/bin/python3
txt = "hello b2b2b2 and 3g3g3g"
x = txt.title()
print(x)
Output:
Python String title() Example#3
Use Regex to resolve Python String title() method exceptions.
import re
def to_title(string):
regex = re.compile("[a-z]+('[a-z]+)?", re.I)
return regex.sub(lambda grp: grp.group(0)[0].upper() + grp.group(0)[1:].lower(),
string)
print(to_title("I won't be working tomorrow, good job."))
Output: