是否可以让用户使用 input() 在字符串之间输入值?

例如,使用 input() 函数,如:

input("Type your age:" +"years old")`

当我运行它时,我希望用户在 age: 和 years 之间输入他们的年龄,但是,当我运行它时,用户必须在岁后输入他们的年龄。是否有可能让用户可以在年龄:和年份之间输入他们的年龄


慕尼黑5688855
浏览 167回答 4
4回答

DIEA

基本上,没有。当您使用 input([prompt]) 时,您的“输入您的年龄:”+“岁”成为提示。输入总是在最后接受值。我的问题变成了,你真的需要“岁”的部分吗?你总是可以做这样的事情:age = input('How old are you?')print(f'You are {age} years old!')

慕盖茨4494581

实际上是的,但它不太实用:x = input("           years old \rAge: ") print(x)这里的技巧是使用\r(回车) 将光标返回到行首。请注意,如果用户键入的内容大于给定的空格数,它将覆盖文本“岁”。

守候你守候我

您可以使用 的实现getch从用户读取单个字符。这是解决方案:import sysprint("Type your age:", end=" ")sys.stdout.flush()c = getch()print(c + " years old")首先,你得到:Type your age: ▯然后,您按一个字符(您可以使用 2 次调用getch来获取 2 个字符)。它打印:Type your age: 9 years old编辑但是,这样做的经典方法是:while True:&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; age = int(input("Type your age: "))&nbsp; &nbsp; except ValueError:&nbsp; &nbsp; &nbsp; &nbsp; print("This is not an integer")&nbsp; &nbsp; &nbsp; &nbsp; print()&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; if 1 <= age <= 120:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; print("please, enter your age between 1 and 120 years")&nbsp; &nbsp; &nbsp; &nbsp; print()print("You are {age} years old.".format(age=age))

当年话下

是的,但您必须学习如何打印、退格和从那里获取输入。处理这个问题的常用方法是准确地表达你的问题:input("Enter&nbsp;your&nbsp;age&nbsp;in&nbsp;years,&nbsp;a&nbsp;whole&nbsp;number:&nbsp;")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python