0

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]
DYZ
  • 55,249
  • 10
  • 64
  • 93
Akash
  • 1
  • 1

1 Answers1

1

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 ")
Mahmoud Elshahat
  • 1,873
  • 10
  • 24
  • Thanks mate!!! But still I am facing the same issue .Its still taking enter as a new input – Akash Apr 05 '19 at 06:22
  • do you mean you want to neglect enter only input i.e. if user hit Enter with a blank password? – Mahmoud Elshahat Apr 05 '19 at 06:36
  • @Akash i edited the answer see if it solves your problem of getting an extra enter as a new input – Mahmoud Elshahat Apr 05 '19 at 06:57
  • I am still seeing \r being taken as input... I am not sure ,why this extra command ['\r' in this case ] is being taken automatically. Enter your password: The password dd is not as per rules Enter your password: The password is not as per rules Enter your password:[prompting agian to enter valid input] This is what I am seeing... – Akash Apr 05 '19 at 08:53