Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Titlecasing a string with exceptions

Is there a standard way in Python to titlecase a string (i.e. words start with uppercase characters, all remaining cased characters have lowercase) but leaving articles like and, in, and of lowercased?

like image 798
yassin Avatar asked Sep 16 '10 16:09

yassin


People also ask

How do I convert a string to lowercase in Python 3?

The lower() method converts all uppercase characters in a string into lowercase characters and returns it.

How do you print a string in uppercase in Python?

upper() Return Value upper() method returns the uppercase string from the given string. It converts all lowercase characters to uppercase. If no lowercase characters exist, it returns the original string.

How do you make the first letter of a string uppercase in Python?

How do you capitalize the first letter of a string? The first letter of a string can be capitalized using the capitalize() function. This method returns a string with the first letter capitalized. If you are looking to capitalize the first letter of the entire string the title() function should be used.

How do you use case in a sentence in Python?

In Python, the capitalize() method returns a copy of the original string and converts the first character of the string to a capital (uppercase) letter while making all other characters in the string lowercase letters.


1 Answers

There are a few problems with this. If you use split and join, some white space characters will be ignored. The built-in capitalize and title methods do not ignore white space.

>>> 'There     is a way'.title() 'There     Is A Way' 

If a sentence starts with an article, you do not want the first word of a title in lowercase.

Keeping these in mind:

import re  def title_except(s, exceptions):     word_list = re.split(' ', s)       # re.split behaves as expected     final = [word_list[0].capitalize()]     for word in word_list[1:]:         final.append(word if word in exceptions else word.capitalize())     return " ".join(final)  articles = ['a', 'an', 'of', 'the', 'is'] print title_except('there is a    way', articles) # There is a    Way print title_except('a whim   of an elephant', articles) # A Whim   of an Elephant 
like image 81
dheerosaur Avatar answered Oct 05 '22 09:10

dheerosaur