python string/list 中的特定字符仅大写

Upper case only on specific characters in python string/list

我正在学习 python 列表和字符串函数。我需要写一个特定的函数。我的函数 return 正确执行了 Else 任务。但是,我不能只将给定句子中每个单词的第一个和最后一个字母大写。谢谢你的帮助,我只能使用提示中给出的基本功能。

任务如下: 如果给定的句子以*开头,则句子中每个单词的首尾字母大写,return不带*的句子。 Else,连接给定句子中的所有单词,用逗号分隔,returns 结果。

例如 如果我们调用 capitalize_or_join_words("*i love python"),我们会在 return 中得到 "I LovE PythoN" . 如果我们调用 capitalize_or_join_words("i love python"),我们将在 [=50= 中得到 "i,love,python" ]. 如果我们调用 capitalize_or_join_words("i love python "),我们将在 [=50= 中得到 "i,love,python" ].

提示: startswith() 函数检查字符串是否以特定字符开头。 capitalize() 函数将 string.The 的第一个字母大写 upper() 函数将字符串中的所有小写字符转换为大写。 join() 函数从多个字符串列表中创建一个字符串

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

这是我想出的:

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)
In [1]: string = "My name is amir saleem"
   ...: ' '.join([i[0].upper()+i[1:-1] + i[-1].upper() for i in string.split()])
Out[1]: 'MY NamE IS AmiR SaleeM'
def capital(strings):
    if strings.startswith("*"):
        strings = strings.replace("*", "")
        strings = result = strings.title()
        result = ""
        for word in strings.split():
            result += word[:-1] + word[-1].upper() + " "
        return result[:-1]
    else:

        strings = strings.split()
        result = ",".join(s)
        return result