【问题标题】:Python 3: How to ignore line breaks when using input()Python 3:使用 input() 时如何忽略换行符
【发布时间】:2017-03-18 06:04:05
【问题描述】:
while count != 5:
input_text = input("Please insert a number of lines of text \n")
if count != 5:
print("Count is " + str(count))
对于上面的代码,当提示提供输入时,如果我粘贴带有多个换行符的文本。代码将运行换行符的数量!我只想让它在整个文本中运行一次。
谁能帮忙?
【问题讨论】:
标签:
python
python-3.x
input
file-io
line-breaks
【解决方案1】:
您可以使用sys.stdin.read(),但这需要您手动发送 EOT 字符:
>>> import sys
>>> x = sys.stdin.read()
the quick brown fox
jumped over the lazy
dog
>>> print(x)
the quick brown fox
jumped over the lazy
dog
>>>
注意,在我粘贴后最后我使用 Enter 然后 ctrl-D。
【解决方案2】:
我没有找到您问题的确切答案,但是我确实注意到,当您在 shell 中复制多行文本时,它只会将第一行文本分配给 input_text,然后再次运行并将第二行分配给input_text,再次运行,第三行 input_text。你看。
我认为输入语句不适用于多行,尽管您肯定可以找到一些解决方法。
这里的代码显示了每次运行循环时变量如何改变你复制到 shell 的下一行:
count = 0
while True:
count += 1
input_text = input("Please insert a number of lines of text \n")
print("Count is " + str(count))
print("what the variable is set to first time its running the loop: ",input_text,"\n")