简体   繁体   English

Python 中的反向词 function 问题

[英]Problem with reverse words function in Python

My code almost works perfectly, with the exception that the first word reversed always 'miss' the last character, the rest of the sentence works fine.我的代码几乎可以完美运行,除了第一个单词总是“错过”最后一个字符之外,句子的 rest 可以正常工作。 Can anyone find the error to debug this code logic?谁能找到调试此代码逻辑的错误?

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

A more idiomatic way to do something like this in Python is to split, reverse and join:在 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

or, in a single expression,或者,在一个表达式中,

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

You can not reverse slice the string past its beginning, it's not possible.您不能将字符串从其开头反向切片,这是不可能的。

Example:例子:

>>>"baby"[3:0:-1]

'yba'

>>>"baby"[3:-1:-1]

''

I think this might be what you are looking for:我认为这可能是您正在寻找的:

reverse = lambda sentence: ' '.join(sentence.split()[::-1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM