在我们班上,我们正在学习python2.7。我正在用vscode测试练习。你知道吗
exercise 1: read user input and print the length. If the user write exit the program finish.
我的代码如下:
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
example: if i write foo the output is 4 and no 3. When i write exit i don't go out from the while and the output is 5.
我哪里错了?你知道吗
我错过了一个模块?你知道吗
谢谢你的帮助
我不确定为什么会发生这种情况,而且我没有访问windows机器进行测试/验证,但是根据上面的评论,在您使用的python版本上,
raw_input
似乎只剥离换行符(\n
),而不是回车符(\r
)。Windows使用\r\n
,而unix使用\n
。当原始输入返回时,\r
仍然在字符串上,因此额外的字符。cli中一种有用的调试技术是对值使用函数repr()
,以查看它是如何表示的。这有助于定位字符串中的任何杂散控件或不可见字符。你知道吗函数
rstrip()
将删除字符串右侧的所有空白,在这种情况下,应该安全地删除多余的\r
。如果此代码在类似*nix的系统上运行,也应该是安全的,因为rstrip()
只会删除存在的空白。您还可以指定一组要剥离的char,因此如果您想变得迂腐,可以使用rstrip("\r")
。你知道吗应该在保持不同版本的兼容性的同时修复此问题。你知道吗
相关问题 更多 >
编程相关推荐