Learning Python regex, why can’t I use AND operator in if statement?

I’m trying to create a very basic mock password verification program to get more comfortable with meta characters. The program is supposed to take an input, use regex to verify it has at least one capital letter and at least one number, then return either “Password created” if it does, or “Wrong format” if it doesn’t. I’m trying to use an AND statement inside of my conditional statement and I know it’s not optimal, I just don’t understand why it doesn’t work at all.

Here’s the code:

import re
password = input()

#check input for at least one cap letter and at least one number

if re.match(r"[A-Z]*", password) and re.match(r"[0-9]*", password):
    print("Password created")
else:
    print("Wrong format")

Edit: To everyone helping and asking for clarification, I’d like to apologize. The original code did not have the asterisks because I’m new to StackOverflow and did not use the correct formatting. I’m also new to asking coding questions so I’ll give some more context as requested. I’ve since changed the code to this:

import re
password = input()

#check input for at least one cap letter and at least one number
if re.search(r"[A-Z]*", password) and re.search(r"[0-9]*", password):
    print("Password created")
else:
    print("Wrong format")

Here are some example inputs and their expected vs actual outputs:

In: “Greatness” Expect: “Wrong format”
Actual: “Password created”
In: “12335” Expect: “Wrong format”
Actual: “Password created”
In: “Gm16gs” Expect: “Password created”
Actual: “Password created”

If I’m missing any more context please let me know as I am still new to this.

Update: I’m a moron. It wasn’t the and, it was the asterisks. Thank you so much everyone. I’ve marked the first answer as correct because the comments show me that I should’ve been using “+” and not “*”

>Solution :

Use re.search to find a match anywhere in the string. re.match will only return a match if the match starts from the beginning of the string.

if re.search("[A-Z]", password) and re.search("[0-9]", password): 

Leave a Reply