python - 如何修复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
解决方案
你必须使用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
。
推荐阅读
- angular - 为什么打字稿在我的 IDE 中给我一个错误,说 Observable 上的属性不存在但显示它们存在?
- mysql - 没有中间表的sql连接(旧数据库)
- javascript - 如何从我的网站中的表单接收消息
- sql - SQL 仅从最大值中获取一列
- abap - 自定义字段未显示在表格输出中
- java - 如何在运行时将元素存储在 Array 中而不知道在 Java 中初始化期间的数组大小?你不能使用 Arraylist
- r - 确定一个值是否与之前匹配的组中的 id 匹配
- html - 在 Outlook 黑色主题模式下使 Outlook HTML 模板按钮背景透明
- react-native - 如何在 const 函数中导航 [react native]
- javascript - ReactJs中保存时获取数据数组