Capitalize only certain specific words in a returned string?

Viewed 163

in my code I have this line which return a string

return item.title().lower()

item is an object, with a title, and we return that string title but in all lowercase.

How can I do something like

return item.title().lower() but if the words (Maxine, Flora, Lindsey) are in that title, keep them uppercase. All the other words, do lowercase

I can use an if statement but I'm not really sure how to capitalize only specific words.

like

names= ("Maxine", "Mrs. Lichtenstein", "string3")
    if any(s in item.title() for s in names):
        return ???

would something like that work? And what could I return?

3 Answers

The following should work (considering that there is no occurence of these words with first character as lowercase (eg maxine) or there is and you want it to upper):

def format(s):
    s=s.lower()
    for i in ('maxine', 'flora', 'lindsey'):
        if i in s:
            s=s[:s.find(i)]+i[0].upper()+i[1:]+s[s.find(i)+len(i):]
    return s

Example:

item.title='My name is Maxine i LIVE IN Flora and I LOVE Lindsey'  
>>> format(item.title)
'my name is Maxine i live in Flora and i love Lindsey'

You're on the right track to use an if statement to check the word against a list of things to keep. Try something like this:

def lowercase_some(words, exclude=[]):
    # List of processed words
    new_words = []
    for word in words:
        if word.lower() in exclude:
            # If the word is in our list of ones to exclude, don't convert
            new_words.append(word)
        else:
            new_words.append(word.lower())

    return new_words

>>> lowercase_some(['TEST', 'WORDS', 'MEXICO'], ['mexico'])
['test', 'words', 'MEXICO']

This can be done in a very Python-ic way with list-comprehension:

def lowercase_some(words, exclude=[]):
    return [word.lower() if word.lower() not in exclude else word for word in words]

you can use this:

names = ['Maxine', 'Flora', 'Lindsey']
if item.title() in names:
    return item.title()
else:
    return item.title.lower()
Related