我编写了一个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(“这是一个测试”)返回这是一个测试
谢谢你的帮助
这是因为
index()
函数返回字符串中该字符的第一个实例的索引。您需要的是使用enumerate编写循环:for index, word in enumerate(s):
这样,您就可以基于从
enumerate()
传递的index
变量来编写逻辑,而不用使用index函数相关问题 更多 >
编程相关推荐