views:

80

answers:

5

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 and like lowercased?

+2  A: 

There are these methods:

>>> mytext = u'i am a foobar bazbar'
>>> print mytext.capitalize()
I am a foobar bazbar
>>> print mytext.title()
I Am A Foobar Bazbar

There's no lowercase article option. You'd have to code that yourself, probably by using a list of articles you want to lower.

nosklo
+2  A: 
capitalize (word)

This should do. I get it differently.

>>> mytext = u'i am a foobar bazbar'
>>> mytext.capitalize()
u'I am a foobar bazbar'
>>>

Ok as said in reply above, you have to make a custom capitalize:

mytext = u'i am a foobar bazbar'

def xcaptilize(word):
    skipList = ['a', 'an', 'the', 'am']
    if word not in skipList:
        return word.capitalize()
    return word

k = mytext.split(" ") 
l = map(xcaptilize, k)
print " ".join(l)   

This outputs

I am a Foobar Bazbar
pyfunc
That's not what I want. I want to get "I am a Foobar Bazbar"
Yassin
@Yassin Ezbakhe : Edited my answer, this should work for you. The list of articles can be easily lifted from any dictionary
pyfunc
+1  A: 
 not_these = ['a','the', 'of']
thestring = 'the secret of a disappointed programmer'
print ' '.join(word
               if word in not_these
               else word.title()
               for word in thestring.capitalize().split(' '))
"""Output:
The Secret of a Disappointed Programmer
"""

The title starts with capitalized word and that does not match the article.

Tony Veijalainen
+2  A: 

Use the titlecase.py module! Works only for English.

>>> from titlecase import titlecase
>>> titlecase('i am a foobar bazbar')
'I Am a Foobar Bazbar'
Etienne
+1, nice module!
Yassin
+1  A: 

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 in exceptions and word or 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
dheerosaur
+1 for the "sentence starting with an article" case
Yassin