【发布时间】:2019-02-27 06:45:10
【问题描述】:
在我的课堂上,我们正在学习 python 2.7。我正在使用 vscode 来测试练习。
练习1:读取用户输入并打印长度。如果用户写 退出程序完成。
我的代码如下:
myexit=False
while (myexit!=True):
#read user input
txt=raw_input("write a string or write exit to go out: ")
#print the user input string
print txt
if (str(txt)=='exit'):
myexit=True#exit from while
else:
print len(txt) #print the string length
print "finish"
当我测试代码我总是得到字符串的长度+1
示例:如果我写 foo 输出是 4 而不是 3。当我写 exit i 从while中不要出去,输出是5。
我哪里错了?
我错过了一个模块?
感谢您的帮助
【问题讨论】:
-
我在 Python 2.7 和 Python 3.7 中尝试了相同的代码,其中 raw_input() 被重命名为 input() 并且没有任何问题。
-
我无法在 REPL 中重现这个。但请尝试使用
print repr(text)来查看字符串中的确切内容 -
感谢您的回复,@Doon 我尝试了 print repr(txt) 并且我得到了:例如我写了我的并且在输出中我得到了我的\r。为什么?
-
嗯
\r是回车。你在什么操作系统上运行?您是通过 VScode 还是通过 CLI/Termina/CMD 运行文件。简短的回答是我猜你正在使用 Windows。\r\n是标准 Windows EOL,而 unix 使用\n。 raw_input 正在剥离换行符,但回车。我不知道为什么 -
另一种选择是使用
rstrip()从行尾删除 \r。
标签: python python-2.7 visual-studio-code