首页 > 解决方案 > Python中的反向单词功能问题

问题描述

我的代码几乎可以完美运行,除了第一个单词反转总是“错过”最后一个字符之外,句子的其余部分都可以正常工作。谁能找到调试此代码逻辑的错误?

def reverseWords(str):

    str_len = len(str)
    str = str[str_len-1::-1]

    str_end = ''
    stop = 0
    index = 0

    for i in range(str_len):

        if (str[i] == ' '):
            index = i - 1
            str_end += str[index:stop:-1] + ' '
            stop = i

        elif (i == str_len-1):
            index = i
            str_end += str[index:stop - 1:-1]

    return str_end

print(reverseWords("The greatest victory is that which requires no battle"))
output: battl no requires which that is victory greatest The

标签: python

解决方案


在 Python 中执行此类操作的一种更惯用的方法是拆分、反转和连接:

def reverse_words(text):
   words = text.split(' ')
   reversed_words = []
   for word in words:
       reversed_words.append(word[::-1])
   reversed_text = ' '.join(text)
   return reversed_text

或者,在一个表达式中,

def reverse_words(text):
    return ' '.join(w[::-1] for w in text.split(' '))

推荐阅读