我有以下代码:
age = raw_input("How old are you? ")
height = raw_input("How tall are you? ")
weight = raw_input("How much do you weigh? ")
print " So, you're %r old, %r tall and %r heavy." %(age, height, weight)
好的,raw_input
函数可以标准输出而不带尾随换行符。然后该函数从输入中读取一行,将其转换为字符串(剥离尾随换行符),然后返回该行。
我不明白为什么每条提示信息都显示在一个新行上,因为raw_input只返回一个字符串。它没有添加换行符,代码中没有\n
。
答案 0 :(得分:4)
当您输入对raw_input()的响应时,您可以通过输入换行符来完成。由于您输入的每个字符也会在您键入时显示,因此新行也会显示。
如果您修改了python内置并更改了raw_input,则可以将其终止于'。'而不是'\ n'。交互可能如下所示:
How old are you? 12.How tall are you? 12.How much do you weigh? 12. So you're ...
答案 1 :(得分:1)
这是使用msvcrt在Windows中执行此操作的方法。您可以使用curses库在Mac或unix上执行类似的操作。
import msvcrt
import string
print("How old are you? "),
age = ''
key = ''
while key != '\r':
key = msvcrt.getch()
age += key
print("How tall are you? "),
key = ''
height = ''
while key != '\r':
key = msvcrt.getch()
height += key
print("How much do you weigh? "),
key = ''
weight = ''
while key != '\r':
key = msvcrt.getch()
weight += key
print "\n So, you're %r old, %r tall and %r heavy." %(string.strip(age), string.strip(height), string.strip(weight))
示例输出如下所示:
How old are you? How tall are you? How much do you weigh?
So, you're '37' old, "6'" tall and '200' heavy.