【每日一题0612】字符串操作练习

题目:给定一段英文文本(单词间都是空格分隔),请编写一个函数,将每个单词的首字母转成大写。

def to_capital(words):
    # your codes

示例:

输入:"hogwarts school of witchcraft and wizardry"
输出:"Hogwarts School Of Witchcraft And Wizardry"

手机上手码的,缩进可能不标准

def to_capital(worlds):
print (worlds.title())

def to_capital(words):
    return ' '.join([x.capitalize() for x in words.split()])

assert to_capital('hogwarts school of witchcraft and wizardry') == 'Hogwarts School Of Witchcraft And Wizardry'
"""
题目:给定一段英文文本(单词间都是空格分隔),请编写一个函数,将每个单词的首字母转成大写。

def to_capital(words):
    # your codes
示例:

输入:"hogwarts school of witchcraft and wizardry"
输出:"Hogwarts School Of Witchcraft And Wizardry"
"""


def to_capital(words):
    def upper(word):
        if len(word) >= 1:
            word = word[0].upper() + word[1:]
        return word

    return " ".join([upper(i) for i in words.split(" ")])


assert to_capital('hogwarts school of witchcraft and wizardry') == "Hogwarts School Of Witchcraft And Wizardry"

print(strl.title())

def  fn(ss):
    res=''
    sss=ss.split(' ')
    for i in range(len(sss)):
        a=sss[i].capitalize()  #首字母大写然后赋值给a
        if i<len(sss)-1:
            res=res+a+' '
        else:
            res = res + a
    return res
a ="hogwarts school of witchcraft and wizardry"
print(a.title())

还有这么简单的方法

关闭