gpt4 book ai didi

python - 交替字符串大小写的问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:35:44 24 4
gpt4 key购买 nike

通过 CodeWars 网站上的练习,我需要帮助为一个简单的功能指明正确的方向:

Write a function toWeirdCase (weirdcase in Ruby) 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(' ').

我目前的代码是这样的:

def to_weird_case(string):
#TODO
new_string = ''
add = 0
for letter in range(len(string)):
if string[letter] == ' ':
add += 1
new_string += string[letter]
continue

if (letter+add)%2 == 0:
new_string += string[letter].upper()
else:
new_string += string[letter].lower()

print("Returning: " + new_string)
return new_string

我试图在考虑空格的同时遍历每个字母,但我不确定如何“跳过”空格,这就是我的功能困惑的原因吗?如果有人能为我指出正确的方向,那将很有帮助,谢谢。

最佳答案

def to_weird_case(string):
#TODO
counter = 0
new_string = ''
add = 0
for letter in range(len(string)):
if string[letter] == ' ':
new_string += string[letter]
continue

if (counter)%2 == 0:
new_string += string[letter].upper()
else:
new_string += string[letter].lower()
# Increment counter after one place as 0th position is even
counter = counter + 1
print("Returning: " + new_string)
return new_string


to_weird_case("HELLO MY NAME IS abcdefghijk")

输出:返回:HellO mY nAmE is aBcDeFgHiJk

关于python - 交替字符串大小写的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44535151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com