Printing String after the user input on the same line

Question:

so basically i want to use the python input() function to get a velocity input from the user. After the user types the number i want to display a nit like m/s behind the user input.
I thought i can do something like this:

velocity = input("Please enter a velocity: ", end='')
print("m/s")

but end=” only works with print() and not with input(). Do you have any other ideas?
Thank you in advance.

Asked By: Malte Rothkamm

||

Answers:

You are already reading the user input into a variable called velocity. So you already have the value, you just need to print it and append m/s to it.

Here’s a way to do it –

velocity = input("Please enter a velocity: ")
print(velocity, end="m/sn")

n is newline character and is adding a newline after m/s
Here’s a test run –

~ python my_test.py
Please enter a velocity: 67
67m/s

For printing you can use different versions –

print(f"{velocity}m/s")
print("{}m/s".format(velocity))

Based on comments, the OP wants the input field itself to be updated with that value. This behaviour is not supported by the input() function by default, and would involve terminal text manipulation.

You can use curses to manipulate the strings.


If you only want to update the previous line once the user has given input, you can use the ANSI escape code for going to previous line(33[F) –

velocity = input("Please enter a velocity: ")
print(f"33[FPlease enter a velocity: {velocity}m/s")

Try running above code, after you press enter, the previous line would be replaced and m/s would be appended to the original input.

Sample run, while entering the value –

~ python my_test.py
Please enter a velocity: 67

after you press Enter, the previous line is updated in place –

~ python my_test.py
Please enter a velocity: 67m/s
Answered By: Jay

The easiest way to do it is, to take the input in the print method.
i.e

print(input("Please enter a velocity: "), "m/s")

OutPut

Please enter a velocity: 64
64 m/s
Answered By: Himanshu Joshi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.