【问题标题】:How to print at the same line of an input?如何在输入的同一行打印?
【发布时间】:2021-12-04 21:37:12
【问题描述】:

输出应该是这样的:

Please enter the miles you drove: 256
Please enter the gallons of gas you put in the tank: 
10.1 You got 25.346534653465348 mpg on that tank of gas.

我这样做了:

miles = float(input("Please enter the miles you drove: "))
gallons = float(input("Please enter the gallons you put in the tank: \n"))
print("You got", miles/gallons, "mpg on that tank of gas.")

但显示的输出是:

Please enter the miles you drove: 256
Please enter the gallons you put in the tank: 
10.1
You got 25.346534653465348 mpg on that tank of gas.

我需要 10.1 和打印在同一行

我该怎么做?

【问题讨论】:

  • 从第二个输入中删除“\n”。
  • 虽然问当然是有道理的,但你为什么要这么做?看起来不太好......你真的应该在一行上打印每个问题,在另一行上打印最终输出......

标签: python


【解决方案1】:

使用input() 函数实际上无法实现,但如果您使用的终端仿真器支持它们,您可以使用ANSI escape sequences。这是一个例子:

miles = float(input("Please enter the miles you drove: "))
gallons = input("Please enter the gallons you put in the tank: \n")
offset = len(gallons)
gallons = float(gallons)
print(f"\33[1A\33[{offset}C You got { miles / gallons } mpg on that tank of gas.")

\33[1A 序列会将光标向上移动一行,\33[{offset}C 会将光标向右移动第二个输入值的长度。

【讨论】:

  • 这里只回答实际回答问题的...(并且有很好的解释)
  • 请问如何理解这样的偏移量?
【解决方案2】:

请查看这段代码。

miles= float(input("Please enter the miles you drove: "))

gallons = float(input("Please enter the gallons you put in the tank: "))
ratio = miles/gallons
print(" You got",ratio, "mpg on that tank of gas.")

这将按预期为您提供

【讨论】:

  • 不,不会。最后一次打印仍将在新行上
【解决方案3】:

试试这个格式

miles = float(input("Please enter the miles you drove: "))
gallons = float(input("""Please enter the gallons you put in the tank:
"""))
print(f"You got {miles/gallons} mpg on that tank of gas.")

【讨论】:

  • 这不能回答问题。最后一次打印仍将在新行上
【解决方案4】:

#试试这段代码,如果你想把变量放在那里,也不要害怕把 (f' 放在打印行的开头!

miles = float(input("Please enter the miles you drove: "))
gallons = float(input("Please enter the gallons you put in the tank: "))
divide = miles/gallons 
print(f'You got {divide} mpg on that tank of gas.')

【讨论】:

  • 这不能回答问题。最后一次打印仍将在新行上
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-02
  • 2013-05-31
相关资源
最近更新 更多