【每日一题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'
1 个赞
"""
题目:给定一段英文文本(单词间都是空格分隔),请编写一个函数,将每个单词的首字母转成大写。

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())

还有这么简单的方法

return words.title()
def to_capital(words):
    return ' '.join(w.capitalize() for w in words.split(' '))

def fun():
s = input(“请输入一串英文:”)
sa=s.title()
return sa
print(fun())

def to_capital(words):
    return ''.join([word.upper() if (idx == 0 or words[idx - 1] == ' ') else word for idx, word in enumerate(words)])


assert to_capital("hogwarts school of witchcraft and wizardry") == "Hogwarts School Of Witchcraft And Wizardry"
    public static String toCapital(String words) {
        List<String> res_list = new ArrayList<String>();
        String[] words_list = words.split(" ");
        for (String word : words_list) {
            word = word.substring(0, 1).toUpperCase() + word.substring(1);
            res_list.add(word);
        }
        return String.join(" ", res_list);
    }