Reputation: 3515
This is actually a question I've had since I first started learning Python a year ago. And it is the following: How can I call the input
function and have the users type their entry at some point other than the end of the prompt
?
To clarify, say I had the string
'Enter file size: MB'
And when called I would want the text to be inserted like so:
Enter file size: 62 MB
Is it possible to recreate this behavior in a function call like the following?
input('Enter file size: {} MB')
# where Python would interpret
# the {} as the position to input text
Upvotes: 6
Views: 218
Reputation: 868
This works on both Windows and Linux:
import sys
print(" MB\rEnter file size: ", end = "")
file_size = sys.stdin.readline()[:-1]
On Linux (not Windows), you can also use input(" MB\rEnter file size: ")
.
Here's a function that makes it a little easier to use:
import sys
def input_multipart(prefix, gap_length, suffix):
print(" " * (len(prefix) + gap_length) + suffix + "\r" + prefix, end = "")
return sys.stdin.readline()[:-1]
Usage:
file_size = input_multipart("Enter file size: ", 3, "MB")
Output:
Enter file size: MB
Upvotes: 3
Reputation: 3018
(Linux)
EDIT : One way to do it is :
file_size=input("Enter file size : MB\rEnter file size : ")
You can also try :
file_size=input("Enter file size: MB \x1B[6D")
#Enter file size: 12 MB
In \x1B[6D
the 6 here moves the cursor six places backwards and lets the user enter the value after the :
but before the MB
Upvotes: 2