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.
Read More Python String Methods
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