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
Python input() function is used to take user input. By default, it returns the user input in form of a string.
In Python, we use input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function convert it into a string.
In Python, we use the print() function to output data to the screen. Sometimes we might want to take the input from the user. We can do so by using the input() function. Python takes all the input as a string input by default.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With