繁体   English   中英

以下python代码段是做什么的?

[英]What does the following python code snippet do?

def reverse(text):
    final_string = ""
    count = len(text)
    while count > 0:
        final_string += text[len(text)-1]
        text = text[0:len(text)-1]
        count -= 1
    return final_string

这是代码片段。 我知道它会反转字符串“ text”,但似乎无法理解它是如何做到的。

def reverse(text):
    final_string = "" 
    count = len(text) # sets the counter variable to the length of the string variable
    while count > 0: # starts a loop as long as our counter is higher than 0
        final_string += text[len(text)-1] #copies the last letter from text to final string
        text = text[0:len(text)-1] #removes the last letter from text
        count -= 1 #decrements the counter so we step backwards towards 0
    return final_string

final_string += text[len(text)-1得到的最后一个字符text并将其添加到年底final_string

text = text[0:len(text)-1]删除text的最后一个字符; 基本上,它只是通过将字符添加到final_string来缩短text

count -= 1倒数至零。 当达到零时, text为0长度,并且final_string text所有字符添加到其中。

它将text的最后一个字符重复添加到final_text ,然后缩短text直到它不再包含字符为止。

它需要一个答案字符串,找到原始文本的长度并将其放入可变计数中。 然后,它使用此变量一次将字符串从反向字符到前一个字符放置,同时从原始字符串中删除字符。

更好的解决方案是

reverse_text = text[::-1]

这就是反转字符串所需的全部。

暂无
暂无

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

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