Fixing the Limitations of title() Method

Now let’s look at the technique that you can use and avoid this unexpected behaviour of string title() function.

Using Regex to fix the unexpected behavior of String title() Method.

Python3




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."))


Output:

I Won't Be Working Tomorrow.

In this article we have covered the definition, syntax and uses of string title() method in Python. We also covered the limitation of this function and how to work around it.

String title() function is very useful string method for text formatting.

Similar Reads:

Python String Title method

Python String title() method returns a new string after converting the first letter of every word to uppercase(capital) and keeping the rest of the letters lowercase.

Example: Make string title case

Python3




print("usE stRing title Method".title())


Output

Use String Title Method

Similar Reads

String title() Method Syntax

...

What is String title() Method?

string.title()...

More Example on String title() Method

String title() is an in-built function in Python that is used to change text in title format. It converts the first letter of every word to uppercase and other letters to lowercase and then returns this new string....

Limitations of String title() Method

...

Fixing the Limitations of title() Method

Here are some more examples on string title() method, for better understanding:...

FAQ on Python title() method

...