0
Can anyone help make this code shorter?
Its a password validator in regex &python it works but it quite long i would love any ideas to shorten the lines of code https://code.sololearn.com/ct8i16N6FwQx/?ref=app
4 Answers
+ 3
Hi! For now you donât need any lowercase letters in the password, but you must have uppercase letters. Is that how you want it to work?
I donât think the code is extremly long. I think it better to focus on readability according to PEP8. That will give more than what a shorter code will do.
For example:
write:
pat4 = râ[a-z]â
re.search(pattern, pas)
instead of:
pat4=râ[a-z]â
re.search(pattern,pas)
It is not a (good) way to do the code shorter through writing âelse:â and âprint('invalid')â at the same line, like this:
if a > b:
do_this()
else: print('invalid')
Itâs is a good (and correct) way to use a line for it:
if a > b:
do_this()
else:
print('invalid')
+ 5
Advice: Don't.
Don't make it shorter, rather, make it longer. You have several reasons to reject a password. These should be differentiated. Yes, you can make this shorter, with a single line regex. But it will be hard to read, hard to maintain, hard to understand, hard to change, and error prone. I personally would even make it a pipe-and-filter pattern with several filters attachable to the stream. Each well tested, each concerned with one aspect, each easy to understand, easy to change, easy to adjust by adding or removing filters.
Much better.
Incidentally: Thank you for reading if you have come to this point :) Also, your password check is faulty, as it does not verify that a lowercase character is a part of the password. For example SOLOLEARN#18 will pass, but your task requirements specify "uppercase & lowecase (sic!) char".
+ 2
# last lines
if re.search(r"[^A-Z0-9a-z]", pas): print(f'{pas} is valid')
else: print('invalid')
+ 2
Wow great help guys thank you