Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

input() call where text is typed at custom position in the string

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
like image 207
N Chauhan Avatar asked Sep 08 '18 14:09

N Chauhan


People also ask

What does the Python input () function do?

Python input() function is used to take user input. By default, it returns the user input in form of a string.

How do you input a string in Python?

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.

How do you print and input in python?

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.


1 Answers

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
like image 132
anonymoose Avatar answered Oct 01 '22 22:10

anonymoose