Akash
Akash

Reputation: 1

How to remove \r character from the getpass prompt

I have written a code which actually matches the patter RegEx in Python. I have used getpass library to prompt the user to enter the password.But if the user enters the wrong password[say 'HH'-which is invalid password].Once the user hits enter after typing the password,the get pass is taking "HH" and "enter as \r" [two different inputs]. Now I need a way to find out how to seperate '\r' from being passed as an input.

I have tried using strip function to remove '\r' but was unsuccessful

import getpass
import re
loopVar=True

while loopVar:

    password = getpass.getpass("Enter your password: ")
    password.rstrip('\r')
    pattern=re.match(r'(?=.{5,32}$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])',password)

    if pattern:
        print ("The password mateches as per standards")
        loopVar=False
    else:
        print ("The password "+ password +" is not as per rules ")
Enter your password:
The password hh is not as per rules
Enter your password:(this is taking \r as input character and I dont need this)
The password  is not as per rules

Enter your password:[Prompting user to input]

Upvotes: 0

Views: 345

Answers (1)

Mahmoud Elshahat
Mahmoud Elshahat

Reputation: 1959

You are too close :)

modify your code from:

password.rstrip('\r')

to

password = password.rstrip('\r')

Explanation: from python docs,

str.rstrip([chars]): Return a copy of the string with trailing characters removed.

because string is immutable in python so you need to assign this copy to your variable again

Edit: responding to the issue of getting double entries when user write password and hit enter, one entry has a password string and second is bare enter code '\r', you can add if statement to filter out second input example:

password = getpass.getpass("Enter your password: ")

if password != '\r':  # filter out echo input
    password.rstrip('\r')
    pattern=re.match(r'(?=.{5,32}$)(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[^A-Za-z0-9])',password)

    if pattern:
        print ("The password mateches as per standards")
        loopVar=False
    else:
        print ("The password "+ password +" is not as per rules ")

Upvotes: 1

Related Questions