简体   繁体   English

如何在输入的同一行打印?

[英]How to print at the same line of an input?

The output should be like this: output 应该是这样的:

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.

I did this:我这样做了:

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.")

but the output shown is:但显示的 output 是:

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.

I need for the 10.1 and the print to be on the same line我需要 10.1 和打印在同一行

How can I do that?我怎样才能做到这一点?

Please check this out a piece of code.请检查这段代码。

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.")

This will give you as expected这会给你如预期的那样

Try this format试试这个格式

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.")

This is not really possible to achieve with the input() function, but you can use ANSI escape sequences , like this:使用input() function 这实际上是不可能实现的,但是您可以使用ANSI 转义序列,如下所示:

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.")

The \33[1A sequence will move the cursor up one line, and \33[{offset}C will move it to the right by the length of the second entered value. \33[1A序列会将 cursor 向上移动一行,而\33[{offset}C会将其向右移动第二个输入值的长度。

#Give this code a try, also don't be afraid to put (f' at the beginning of your print lines if you want to put variables in there! #试试这段代码,如果你想把变量放在那里,也不要害怕把 (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.')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM