Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Title case with a list of exception words

Im trying to come up with something that will "title" a string of words. It should capitalize all words in the string unless given words not to capitalize as an argument. But will still capitalize the first word no matter what. I know how to capitalize every word, but I dont know how to not capitalize the exceptions. Kind of lost on where to start, couldnt find much on google.

  def titlemaker(title, exceptions):
      return ' '.join(x[0].upper() + x[1:] for x in title.split(' '))

or

return title.title()

but I found that will capitalize a letter after an apostrophe so I dont think I should use it. Any help on how I should take into account the exceptions would be nice

example: titlemaker('a man and his dog', 'a and') should return 'A Man and His Dog'

like image 674
CDog Avatar asked Mar 14 '23 14:03

CDog


2 Answers

def titlemaker(title,exceptions):
    exceptions = exceptions.split(' ')
    return ' '.join(x.title() if nm==0 or not x in exceptions else x for nm,x in enumerate(title.split(' ')))

titlemaker('a man and his dog','a and') # returns "A Man and His Dog"

The above assumes that the input string and the list of exceptions are in the same case (as they are in your example), but would fail on something like `titlemaker('a man And his dog','a and'). If they could be in mixed case do,

def titlemaker(title,exceptions):
    exceptionsl = [x.lower() for x in exceptions.split(' ')]
    return ' '.join(x.title() if nm==0 or not x.lower() in exceptions else x.lower() for nm,x in enumerate(title.split(' ')))

titlemaker('a man and his dog','a and') # returns "A Man and His Dog"
titlemaker('a man AND his dog','a and') # returns "A Man and His Dog"
titlemaker('A Man And His DOG','a and') # returns "A Man and His Dog"
like image 160
Matthew Avatar answered Mar 25 '23 06:03

Matthew


Try with this:

def titleize(text, exceptions):
    exceptions = exceptions.split()
    text = text.split()
    # Capitalize every word that is not on "exceptions" list
    for i, word in enumerate(text):
        text[i] = word.title() if word not in exceptions or i == 0 else word
    # Capitalize first word no matter what
    return ' '.join(text)

print titleize('a man and his dog', 'a and')

Output:

A Man and His Dog
like image 38
Andrés Pérez-Albela H. Avatar answered Mar 25 '23 06:03

Andrés Pérez-Albela H.