Search code examples
pythonstringlistuppercase

Upper case only on specific characters in python string/list


I am learning python list and string functions. I need to write a specific function. My function returns correctly the Else task. However, I am not able to capitalize only the first and last letter of each word in the given sentence. Thank you for your help, I can only use basic functions as given in the hints.

Here is the task: If the given sentence starts with *, capitalizes the first and last letters of each word in the sentence, and returns the sentence without *. Else, joins all the words in the given sentence, separating them with a comma, and returns the result.

For example if we call capitalize_or_join_words("*i love python"), we'll get "I LovE PythoN" in return. If we call capitalize_or_join_words("i love python"), we'll get "i,love,python" in return. If we call capitalize_or_join_words("i love python "), we'll get "i,love,python" in return.

Hints: The startswith() function checks whether a string starts with a particular character. The capitalize() function capitalizes the first letter of a string.The upper() function converts all lowercase characters in a string to uppercase. The join() function creates a single string from a list of multiple strings

def capitalize_or_join_words(sentence):

if sentence.startswith('*'):
    s = sentence.replace('*','')
    s2 = s.split()
    
    s3 = []

    for word in s2:
        s3 += word.capitalize()
    
    temp = ",".join(s3)
    sentence_revised = temp
    
else:
    
    s = sentence.split()
    sentence_revised = ",".join(s)

return sentence_revised

Solution

  • Here is what I came up with:

    def capitalize_word(word):
        if not word:
            return ''
        if len(word) < 3:
            return word.upper()
        return word[0].capitalize() + word[1:-1] + word[-1].capitalize()
    
    def capitalize_or_join_words(sentence):
        if sentence.startswith('*'):
            words = sentence.replace('*', '').split()
            return ' '.join(capitalize_word(word) for word in words)
    
        words = sentence.split()
        return ','.join(words)