不使用 reversed() 或 [::-1] 来反转字符串? [英] Reverse a string without using reversed() or [::-1]?

查看:33
本文介绍了不使用 reversed() 或 [::-1] 来反转字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个奇怪的 Codecademy 练习,它需要一个将字符串作为输入并以相反顺序返回它的函数.唯一的问题是你不能在 stackoverflow 上使用反向方法或常见答案,[::-1].

I came across a strange Codecademy exercise that required a function that would take a string as input and return it in reverse order. The only problem was you could not use the reversed method or the common answer here on stackoverflow, [::-1].

显然在现实的编程世界中,人们很可能会选择 extended slice 方法,甚至使用 reversed 函数,但也许在某些情况下这不起作用?

Obviously in the real world of programming, one would most likely go with the extended slice method, or even using the reversed function but perhaps there is some case where this would not work?

我在下面以问答的形式提供了一个解决方案,以防将来对人们有所帮助.

I present a solution below in Q&A style, in case it is helpful for people in the future.

推荐答案

你也可以用递归来实现:

You can also do it with recursion:

def reverse(text):
    if len(text) <= 1:
        return text

    return reverse(text[1:]) + text[0]

以及字符串 hello 的简单示例:

And a simple example for the string hello:

   reverse(hello)
 = reverse(ello) + h           # The recursive step
 = reverse(llo) + e + h
 = reverse(lo) + l + e + h
 = reverse(o) + l + l + e + h  # Base case
 = o + l + l + e + h
 = olleh

这篇关于不使用 reversed() 或 [::-1] 来反转字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆