[目前,我在cordwarrior中处理奇怪的案件问题。问题在于,将一个函数写入WeirdCase(在Ruby中为weirdcase),该函数接受一个字符串,并返回相同的字符串,每个单词的所有偶数索引字符均大写,每个单词的所有奇数索引字符均小写。刚说明的索引是从零开始的,因此第零个索引是偶数,因此该字符应大写。
我编写了该函数。它成功地交换了单个单词的大小写,但是不适用于多个单词或一个句子,因此我本来打算应用swapcase,但是它交换了所有不希望的句子单词。我不知道哪种情况适合::
def to_weird_case(string):
tot=""
for i in range(len(string)):
if i%2==0:
tot+=string[i].upper()
if i%2==1:
tot+=string[i].lower()
if string[i]==" " or i%2==1:
to_weird_case(string[i:])
return tot
我得到此类型的错误:
toWeirdCase
should return the correct value for a single word (8 of 8 Assertions)
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'\
链接到问题:https://www.codewars.com/kata/52b757663a95b11b3d00062d/train/python
我想到了另一种划分句子并将功能应用于每个单词的方法。
def swap(string):
tot=""
for i in range(len(string)):
if i%2==0:
tot+=string[i].upper()
if i%2==1:
tot+=string[i].lower()
if i%2==0:
swap(string[i])
return tot
def to_weird_case(string):
new=""
for j in string:
print(swap(j))
print(to_weird_case('ThIs iS A TeSt'))
但是它使所有单词都大写。
def to_weird_case(string): # actually your function
tot=""
for i in range(len(string)):
if i%2==0:
tot+=string[i].upper()
if i%2==1:
tot+=string[i].lower()
if string[i]==" " or i%2==1:
to_weird_case(string[i:])
return tot
def to_weird_case_words(string): # my contribution, so that It work with strings with spaces
return ' '.join([to_weird_case(s) for s in string.split(' ')])
print(to_weird_case('this is a test'))
print(to_weird_case_words('this is a test'))
这里是我所做的解释:首先,有string.split('')组成一个单词列表。使用“这是一个测试”,输出为
[['this','is','a','test']。然后,我用列表理解遍历它,并为每个单词应用您的函数。现在我们有了这个列表:
[['ThIs','Is','A','TeSt']。
现在我们需要加入该列表,在每个单词之间添加空格字符。这是通过''.join(list)完成的。因此,我们现在有了最终输出:
'Thiss a TeSt'
还有其他方法可以执行,但是我想使用您已经完成的操作。
if ch == " ":
string += ch
Flag = True
continue
因为它具有continue
语句