Home >Backend Development >Python Tutorial >How to Customize Default Values for Input in Python?

How to Customize Default Values for Input in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 18:40:02551browse

How to Customize Default Values for Input in Python?

Customizing Default Values for Input in Python

In Python, the default input command (input()) allows you to capture user input. However, you may want to provide a default value that the user can edit or accept.

Surprisingly, the standard input functions, input() and raw_input() lack this feature. Here's a solution that leverages the readline module.

The readline Module

If you're working in a Linux environment, you can utilize the readline module to create a custom input function. The readline module offers line editing and allows you to prefill the input field.

Defining a Custom Input Function

Here's how you can define a custom input function that takes a prompt and an optional prefill value:

<code class="python">import readline

def rlinput(prompt, prefill=''):
   readline.set_startup_hook(lambda: readline.insert_text(prefill))
   try:
      return input(prompt)  # or raw_input in Python 2
   finally:
      readline.set_startup_hook()</code>

Usage

To use this custom input function, simply call it like this:

<code class="python">folder_name = rlinput('Folder name: ', 'Downloads')</code>

This code will display a prompt asking for a folder name. It will initially display "Downloads" in the input field, and the user can edit it or press Enter to accept the default.

The above is the detailed content of How to Customize Default Values for Input in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn