这是卡塔:
从https://www.codewars.com/kata/5264d2b162488dc400000001/train/python
Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present.
Examples:
spinWords( "Hey fellow warriors" )
=> returns"Hey wollef sroirraw"
spinWords( "This is a test")
=> returns"This is a test"
spinWords( "This is another test" )
=> returns"This is rehtona test"
这是我的代码:
def spin_words(sentence):
sentence_array = sentence.split()
new_array = []
for word in sentence_array:
if len(word) >= 5:
word = word[::-1]
new_array.append(word)
else:
new_array.append(word)
new_sentence = ''
for word in new_array:
new_sentence += word + ' '
return new_sentence
很难弄清楚为什么不被接受
我找到了让它通过的答案:
您在末尾打印了额外的空格,这是错误的
代码的问题是返回的字符串后面会有一个空格。通过使用
[:-1]
的切片删除它们:为了实现更清洁、更高效的方法:
相关问题 更多 >
编程相关推荐