Display asterisks when user inputs their password in Python

avatar

Borislav Hadzhiev

Last updated: Aug 26, 2022

banner

Photo from Unsplash

Display asterisks when user inputs their password in Python #

To display asterisks when a user inputs their password:

  1. Install the pwinput() module.
  2. Use the pwinput() method to take input from the user and display asterisks.
  3. The method takes a mask argument that can be set to an asterisk.
main.py
import pwinput import getpass # ✅ display * (asterisks) when user types their password password = pwinput.pwinput(prompt='Enter your password: ', mask='*') print(password) # ------------------------------------------------ # ✅ don't display anything when user types their password password = getpass.getpass('Enter your password: ') print(password)
Make sure to install the pwinput module by opening your shell in your project's root directory and running the pip install pwinput command.
shell
pip install pwinput

Now you can use the pwinput method to show asterisks while the user enters their password.

main.py
import pwinput password = pwinput.pwinput(prompt='Enter your password: ', mask='*') print(password)

input password asterisks

The prompt argument is the message that gets displayed and the mask argument is what to mask the user input with.

If you just want to hide the input while the user types their password, use the standard getpass module.
main.py
import getpass password = getpass.getpass('Enter your password: ') print(password)

input password hidden

The getpass() method from the getpass module is used to hide the input while the user types their password.

The getpass module is available in the standard library, so you don't have to install anything.

The getpass method is usually used to prompt the user for a password or other sensitive information.

The argument the method takes is the message that is displayed to the user.

If no message is provided, it defaults to "Password: ".

main.py
import getpass password = getpass.getpass() print(password)

input password hidden default message

We didn't pass a message to the getpass() method so it displayed the default "Password: " message.

You can use the getpass() method to take any other sensitive information from the user without displaying the text, it doesn't have to be a password.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.