【问题标题】:Python 2.7 VSCODE doesn't get the correct length of input stringPython 2.7 VSCODE 没有得到正确长度的输入字符串
【发布时间】: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


【解决方案1】:

我不确定发生这种情况的确切原因,并且我无权访问 Windows 机器进行测试/验证,但根据上面的 cmets,您似乎在使用 raw_input 的 python 版本只是剥离换行符(\n)而不是回车符(\r)。 Windows 使用 \r\n,而 unix 使用 \n。当原始输入返回时,\r 仍然在字符串上,因此额外的字符。在 cli 中一个有用的调试技术是对值使用函数 repr() 来准确查看它是如何表示的。这有助于定位字符串中的任何杂散控件或不可见字符。

函数rstrip() 将删除字符串右侧的所有空格,在这种情况下应该安全地删除杂散的\r。如果此代码在类似 *nix 的系统上运行,它也应该是安全的,因为 rstrip() 只会删除存在的空格。您还可以指定一组要剥离的字符,因此如果您想学究气,可以使用rstrip("\r")

txt=raw_input("write a string or write exit to go out: ").rstrip("\r")

应该解决问题,同时仍然保持不同版本的兼容性。

【讨论】:

    猜你喜欢
    • 2015-10-01
    • 2021-04-20
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多