原题:Write a function that accepts a string, and returns the same string with all even indexed characters in each word upper cased, and all odd indexed characters in each word lower cased. The indexing just explained is zero based, so the zero-ith index is even, therefore that character should be upper cased.
The passed in string will only consist of alphabetical characters and spaces(' '
). Spaces will only be present if there are multiple words. Words will be separated by a single space(' '
).
Examples:
to_weird_case('String'); # => returns 'StRiNg'
to_weird_case('Weird string case') # => returns 'WeIrD StRiNg CaSe'
我的解法:
开始思路想用x.split(' )分解字符串,后来考虑到难以拼接,故转为for循环字符串,连带空格一起处理,用i代表索引值,遇到空格归0,解决问题
def to_weird_case(string):
i = 0
l = []
for x in string:
x = x.lower()
if x == ' ':
l.append(x)
i = 0
continue
if i % 2 == 0:
l.append(chr(ord(x)-32))
else:
l.append(x)
i += 1
return ''.join(l)
大神解法:
def to_weird_case_word(string):
return "".join(c.upper() if i%2 == 0 else c for i, c in enumerate(string.lower()))
def to_weird_case(string):
return " ".join(to_weird_case_word(str) for str in string.split())