带有map和lambda函数的Python字符串问题

2024-09-30 01:30:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个python函数,该函数应该接受一个字符串,并返回相同的字符串,每个单词的大小写都是偶数索引字符,每个单词的大小写都是奇数索引字符
例如:to#u-wird(u-case('wird-string-case')#=>;返回“奇怪的字符串大小写”

def to_weird_case(string):
    s = list(string.split(" "))
    words = []
    for word in s:
        w = map(lambda x: x.upper() if word.index(x)%2 == 0 else x.lower(), word)
        w = "".join(list(w))
        words.append(w)

    #print(words)
    return " ".join(words)

现在我的问题是:一旦超过一个单词被传递,最后一个单词的最后几个字母都被转换成大写,我不明白为什么
例如:to_wird_case(“这是一个测试”)返回这是一个测试

谢谢你的帮助


Tags: to函数字符串gtstring字符单词list

热门问题