You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python字符串反转函数为何逐行输出字符?求修正方案及其他实现

字符串反转问题解答

嘿,作为Python新手遇到这种小问题太正常啦,我来帮你搞定~

问题原因分析

你写的函数之所以会逐行输出每个字符,核心问题在于每次循环都调用了print()函数——Python的print()默认会在输出内容末尾添加换行符,所以每取到一个字符就会单独打印一行。

修正后的函数

我们只需要先把反转后的所有字符拼接成一个完整字符串,最后再一次性打印出来就可以了。这里给你两种修正方案:

方案1:直接拼接字符串

def reverse(word):
    len_word = len(word)
    reversed_str = ""
    x = 0
    while x < len_word:
        x += 1
        index = len_word - x
        reversed_str += word[index]  # 把字符拼接到字符串里
    print(reversed_str)  # 最后统一打印
reverse("123abcd")

方案2:用列表收集字符(效率更高)

因为Python的字符串是不可变对象,反复拼接会生成新的字符串,用列表收集字符再拼接的效率会更高:

def reverse(word):
    len_word = len(word)
    reversed_chars = []
    x = 0
    while x < len_word:
        x += 1
        index = len_word - x
        reversed_chars.append(word[index])  # 把字符添加到列表
    print(''.join(reversed_chars))  # 用join把列表转为字符串再打印
reverse("123abcd")

运行这两个修正后的函数,都会输出你想要的dcba321。

其他字符串反转的实现方式

除了你这种循环写法,Python还有很多更简洁高效的反转方式:

  • 切片语法(最推荐):Python的切片支持[起始:结束:步长],当步长为-1时,就会从后往前取字符,直接生成反转后的字符串:
print("123abcd"[::-1])  # 输出 dcba321
  • 使用reversed()函数:reversed()会返回一个反转字符的迭代器,配合join()可以快速拼接成字符串:
print(''.join(reversed("123abcd")))  # 输出 dcba321
  • 递归实现:如果想练习递归逻辑,可以用这种方式,不过对于超长字符串可能会有栈溢出问题:
def reverse_recursive(word):
    if len(word) == 0:
        return word
    else:
        return reverse_recursive(word[1:]) + word[0]

print(reverse_recursive("123abcd"))  # 输出 dcba321

内容的提问来源于stack exchange,提问作者sumixam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:19:32