首页 > 解决方案 > 如何修复python中的“字符串反转”代码?

问题描述

我用于反转字符串的代码在其他网站上有效,但在 vim 上的 ubuntu 机器上无效。

   wrd=input("Please enter a word ")
    wrd=str(wrd)
    rvs=wrd[::-1]
    print(rvs)
    if wrd == rvs:
        print("This word is a palindrome")
    else:
        print("This word is not a palindrome")

它给出了错误:

python hannah1.py
Please enter a word hannah
Traceback (most recent call last):
  File "hannah1.py", line 1, in <module>
    wrd=input("Please enter a word")
  File "<string>", line 1, in <module>
NameError: name 'hannah' is not defined

标签: python

解决方案


你必须使用raw_input

wrd=raw_input("Please enter a word")
rvs=wrd[::-1]
print(rvs)
if wrd == rvs:
    print("This word is a palindrome")
else:
    print("This word is not a palindrome")

现在它可以工作了,input在 Python 2 中与eval(input(...))在 Python 3 中相同,但是它会尝试查找名为 的变量hannah,而没有任何名为 的变量hannah


推荐阅读