gpt4 book ai didi

python - 如何在字符串中交替使用大写和小写字符?

转载 作者:太空宇宙 更新时间:2023-11-04 11:22:01 25 4
gpt4 key购买 nike

我不明白我在 Codewars 中为 kata 编写的这个函数有什么问题。

这些是说明:

编写一个接受字符串的函数 toWeirdCase(Ruby 中的 weirdcase),并返回相同的字符串,其中每个单词中的所有偶数索引字符都大写,而每个单词中所有奇数索引字符都小写。刚刚解释的索引是从零开始的,所以第零索引是偶数,因此该字符应该是大写的。

传入的字符串将只包含字母字符和空格(' ')。仅当有多个单词时才会出现空格。单词将由一个空格 (' ') 分隔。示例:

weirdcase( "String")#=> 返回 "StRiNg"weirdcase( "奇怪的字符串大小写");#=> 返回 "WeIrD StRiNg CaSe"

这是我编写的函数:

def to_weird_case(string):
return "".join(char.upper() if string.find(char) % 2 == 0 else char.lower() for char in string)

这是我得到的结果:

Time: 695ms Passed: 5 Failed: 8 Exit Code: 1
Test Results:
toWeirdCase
should return the correct value for a single word
Test Passed
Test Passed
Test Passed
'TeST' should equal 'TeSt'
'LookS' should equal 'LoOkS'
Test Passed
Test Passed
'PaSSEd' should equal 'PaSsEd'
should return the correct value for multiple words
'ThIs Is A TesT' should equal 'ThIs Is A TeSt'
'LookS Like you pASSeD' should equal 'LoOkS LiKe YoU PaSsEd'
'ThIs Is ThE FINaL TEsT casE' should equal 'ThIs Is ThE FiNaL TeSt CaSe'
'JuSt kIddINg' should equal 'JuSt KiDdInG'
'Ok fInE YoU ArE DonE now' should equal 'Ok FiNe YoU ArE DoNe NoW'

它看起来似乎通过了一些测试,但它在处理几个单词和每个句子时遇到困难。你们有人知道我做错了什么吗?谢谢。

最佳答案

只需遍历字符,对于奇数或偶数字符,转换为小字符或大字符。我们对列表中的每个单词执行此操作,方法是将字符串拆分为单词列表,然后将字符串拼接回去。

def to_weird_case(s):

li = s.split()
res = []
for s in li:
result = ''
for idx, c in enumerate(s):
if idx%2 == 0:
result += c.upper()
else:
result += c.lower()
res.append(result)
return ' '.join(res)

输出是

print(to_weird_case('String'))
print(to_weird_case("Weird string case"))
print(to_weird_case("TeST"))
print(to_weird_case("LookS"))
print(to_weird_case("PaSSEd"))
print(to_weird_case("ThIs Is A TesT"))
print(to_weird_case("LookS Like you pASSeD"))
print(to_weird_case("ThIs Is ThE FINaL TEsT casE"))
print(to_weird_case("JuSt kIddINg"))
print(to_weird_case("Ok fInE YoU ArE DonE now"))
#StRiNg
#WeIrD StRiNg CaSe
#TeSt
#LoOkS
#PaSsEd
#ThIs Is A TeSt
#LoOkS LiKe YoU PaSsEd
#ThIs Is ThE FiNaL TeSt CaSe
#JuSt KiDdInG
#Ok FiNe YoU ArE DoNe NoW

关于python - 如何在字符串中交替使用大写和小写字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55773815/

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