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

Python字符串反转报错:local variable referenced before assignment如何解决?

Fixing the "local variable 'a' referenced before assignment" Error in Your String Reverse Code

Let's break down what's going wrong here first:

The error you're seeing happens because you're trying to use the variable a in the line a += text[len(text) - i] before you've initialized it. Python has no idea what a is supposed to be at that point—you haven't told it to create an empty string or any other value for a yet.

Here's the fixed version of your original code:

def reverse(text):
    a = ""  # Initialize empty string first!
    for i in range(1, len(text) + 1):
        a += text[len(text) - i]
    return a

print(reverse("Hello World!"))  # Outputs: !dlroW olleH

A more Pythonic way to reverse a string

While your loop approach works, Python has a much simpler built-in way to reverse strings using slicing. This is cleaner and faster for most cases:

def reverse(text):
    return text[::-1]

print(reverse("Hello World!"))  # Same output: !dlroW olleH

The slice [::-1] means "start from the end of the string and move backwards one character at a time"—perfect for reversing strings in one line!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:54:22