Re.match always returning None in python - python

I'm trying to make a very simple regex match ( the negation of all printable anscii characters other then '[' and ']'). When I tested my pattern in regex pal I got the matching that I wanted. Then I moved to my python unit test and my match never returns true
def testChatChars(string):
return re.match('[^\x20-\x5A\x5C\x5E-\x7E]', string) is not None
print("testing Chat validation")
print(testChatChars("") == False)
print(testChatChars("this is a valid chat message") == True)
print(testChatChars("9999abcdefghijklmnopqrxtuvxyz ABCDEFGHIJKLMNOP!##$(^&*(&%$^^)*)!{},.;'\|?/7") == True )
print(testChatChars("this is not [ valid chat message") == False)
print(testChatChars("this is not ] valid chat message") == False)
print(testChatChars("9999abcdefghijklmnopqrxtuvxyz [][][[][]ABCDEFGHIJKLMNOP!##$(^&*(&%$^^)*)!{}[],.;'\|?/7ونِكود碼標準萬國") == False)
Which is returning
False //should be true
False //should be true
False //should be true
True
True
True
re.match is always returning none for some reason.
UPDATE:
tried to change my code in the suggested fashion
new output is
False
False
True
False
False
False

def testChatChars(string):
return re.match(r'[\x20-\x5A\x5C\x5E-\x7E]+$', string) is not None

Related

String index comparison

I am having issues understanding this concept. I am trying to use [-1] index of message[-1] and compare it to the first index message[0] to compare the first letter and the last letter of a string in the function.
def first_and_last(message):
message = " "
if message[0] == message[-1]:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
You are setting your message to the same value every time. You need to instead use the message that is passed to the function.
def first_and_last(message):
if message and message[0] == message[-1]:
return True
else:
return False
print(first_and_last("else"))
print(first_and_last("tree"))
print(first_and_last(""))
True
False
False
You can also get the same result with less work by recognizing that you're performing a test and returning the result of that test.
def first_and_last_improved(message):
return message[0] == message[-1] if message else False
Hey you are initialising the message = " " inside the function so no matter what you sent as a parameter to function it will always initialise it. Remove that line and you will get the expected output.
Firstly, you are overwriting message variable. So whatever you pass to the function returns the same result.
You can think of a string of array of chars. In Haskell string is actually array of chars.
For example... "str" would be ["s", "t", "r"]. So "str"[0] returns s, while -1 returns r.
Also your code can be short by like this.
def first_and_last(message):
return message[0] == message[-1]

python if evaluating True for False value

I have the following object field:
is_vendor = models.BooleanField(default=False)
I have the following if statement:
print(customer.is_vendor) //This prints False
if customer.is_vendor:
print('im a vendor') //This prints even the value above is false
else:
print('im not a vendor')
Why is this occurring?
You have a string in the field -- "False" as opposed to False. Which is cool for Django but not python. Try customer.is_vendor.to_python() instead. That will wrangle it into a boolean for you.
if "False": print 'True!' # is True
if False: print 'True!' # Nope.
if customer.is_vendor.to_python():
print "Is a vendor!"

Logical NOT operation in django

I have a view function that toggles the user state (active-inactive):
def toggle_user_state(request, user_id, current_state):
user = get_object_or_404(User, pk=user_id)
user.is_active = not current_state
user.save()
return HttpResponseRedirect(reverse('cdms:user_details', kwargs={'user_id': user.id}))
If the current_state is True, it works properly by making it False. But if the current_state is False, it remains False.
I have also tried to print(not current_state), but surprisingly not False remains False!
I am not sure why do you need a current_state when you can simply toggle is_active on the user:
def toggle_user_state(request, user_id):
user = get_object_or_404(User, pk=user_id)
user.is_active = not user.is_active # take a NOT of active state here
user.save()
return HttpResponseRedirect(reverse('cdms:user_details', kwargs={'user_id': user.id}))
The current_state captured by the url is always a string. So, in your case it will be either "True" or "False".
not "True" # False
not "False" # False
One solution is this:
if current_state == "True":
user.is_active = False
elif current_state == "False":
user.is_active = True
Another solution is this:
# Define a function to the outer scope
def str_to_bool(s):
if s == 'True':
return True
elif s == 'False':
return False
else:
raise ValueError
# Then inside toggle_user_state do this
try:
user.is_active = not str_to_bool(current_state)
except ValueError:
# handle error here (its neither "True" or "False")
else:
# everything worked. Continue
not False will always return True
>>> not False
>>> True
not 'False' will always return False
>>> not 'False'
>>> False
reason is, any non-empty, string evaluates to boolean True
>>> if 'False':
>>> print 'False in string but not boolean False'
>>> 'False in string but not boolean False'
as a a recap string 'False' does not equal bool False
what I typically do here is write a truthy function that translates any potential intended meaning of true or false into a boolean value
def is_true(value):
if value in ['1', 1, True, 'true', 'yes', 'Yes', 'True']:
return True
return False
so now you can do
def toggle_user_state(request, user_id, current_state):
user = get_object_or_404(User, pk=user_id)
current_state = is_true(current_state) # current_state will now be boolean
user.is_active = not current_state # now, will be boolean opposite
user.save()
return HttpResponseRedirect(reverse('cdms:user_details', kwargs={'user_id': user.id}))

Beginner Python Program Evaluating a Password

I am supposed to write a script with the following criteria:
Write a function called validatePassword that takes a password string as a parameter and returns true or false. The function should only return true if:
The password is at least 8 characters
The password contains at least one number
The password contains at least one upper case letter. Hint: use the isupper() string function.
The password contains a symbol one of the symbols !##$%^&*()+=
I have this so far:
def validatePassword(pswd):
if len(pswd)> 8:
return True
else:
return False
for char in pswd:
if char in '01234567890':
return True
else:
return False
for char in pswd:
if char in '!##$%^&*()_+=':
return True
else:
return False
for char in pswd:
if char.isupper and char .islower:
return True
else:
return False
return True
while False:
print("There was an error with your password")
print (validatePassword(Herseuclds))
I know that print (validatePassword(Herseuclds)) has a syntax error because I am missing the variable but I just don't get how to do this.
def validatePassword(pswd):
if len(pswd) < 8:
return False
number_in_password = False
for char in pswd:
if char in '012356789':
number_in_password = True
if not number_in_password:
return False
symbol_in_password = False
for char in pswd:
if char in '!##$%^&*()_+=':
symbol_in_password = True
if not symbol_in_password:
return False
uppercase_in_password = False
for char in pswd:
if char.isupper():
uppercase_in_password = True
if not uppercase_in_password:
return False
#this only happens if nothing above has disqualified the password
return True
print (validatePassword("herseuc"))
print (validatePassword("herseuclds"))
print (validatePassword("herseuclds!"))
print (validatePassword("herseuclds!123"))
print (validatePassword("herseuclds!123A"))
The main issue with your code is in the last line.
print (validatePassword(Herseuclds))
Right now, the interpreter thinks Herseuclds is a variable, and not a string. If Herseuclds is the password, and not a variable describing the password, then you need quotes around it to make it a string literal.
print (validatePassword("Herseuclds"))
You obviously haven't defined a variable called Herseuclds anywhere in your program, but the program thinks Herseuclds is a variable and not a string, so it throws the error.
Best of luck, and happy coding!
First issue is that you are passing an undeclared variable to your function. See silentphoenix's answer for details.
Secondly, your program only check to see if AT LEAST ONE condition is met, not all.
If a password is 8 characters long, it will return true even if the password doesn't satisfy the other requirements.
I am not going to write your code for you, but I can pseudocode the issue:
def validatePassword(pswd):
if len(pswd) < 8:
return False
# if there isn't a number:
return False
# if there isn't a symbol:
return False
# if there isn't an upper and lowercase:
return False
return True
while True:
print("There was an error with your password")
print (validatePassword("Herseuclds"))
sidenote: watch your indentation :)
Since you can use is.upper() you can also utilize is.digit() to check for numbers instead of having to write down actual digits.
Another thing to speed it up, since they all have to be done at the same time, you can check if the password validates those requirements in one line with any()
def validatePassword(pswd):
l = []
if len(pswd)> 8:
for char in pswd:
l.append(char)
if any(l for x in l if x.isdigit()) and any(l for x in l if x.isupper()) and any(l for x in l if x in '!##$%^&*()_+='):
print('Success')
else:
print('Try again')
while True:
a = input('What is your password?')
validatePassword(a)
At the beginning there's an minimum check to see if the lengeth is greater than 8. If it is, the word gets broken up into a list. This allows any() to be used and checked against the remainding requirements.
def valid_password(password):
return (
# The password is at least 8 characters
len(password) >= 8 and
# The password contains at least one number
any(c in "0123456789" for c in password) and
# The password contains at least one upper case letter
any(c.isupper() for c in password) and
# The password contains a symbol one of the symbols !##$%^&*()+=
any(c in "!##$%^&*()+=" for c in password))
Example:
from getpass import getpass
while not valid_password(getpass('Enter password: ')):
print('invalid password. Try again')

use statement True and False in Python 2.7

i wish to use a statement "True" and "False" for my Python (2.7) command prompt
segmentation_accuracy(reference=REFERENCE, segmented=SEGMENTED, output=OUTPUT, method=METHOD, threshold=THRESHOLD, sep=SEP, header=HEADER)
if header is True print a text file with an header, if header is False print a text file without an header.
in Command Prompt:
REFERENCE = raw_input("Reference (*.shp):")
SEGMENTED = raw_input("Segmented (*.shp):")
METHOD = raw_input("Method (ke, pu, clinton):")
if METHOD != "ke" and METHOD != "pu" and METHOD != "clinton":
raise ValueError("%s is not a valid method" % METHOD)
if METHOD == "ke" or METHOD == "clinton":
THRESHOLD = input("Threshold (0.0 - 1.0):")
if not check_threshold(THRESHOLD):
raise AccuracyException("Threshold of %s is not valid" % THRESHOLD)
else:
THRESHOLD = None
SEP = raw_input("Sep:")
HEADER = raw_input("Header (True/False):")
if HEADER is not True or HEADER is not False:
raise ValueError("%s is not valid" % HEADER)
# output
OUTPUT = raw_input("Output (*.txt):")
when i run the command prompt in windows if i set raw_input("Header (True/False):") True or False, I always get the ValueError
i also used the combination
if HEADER != True or HEADER != False:
raise ValueError("%s is not valid" % HEADER)
with the same problem
The return value from raw_input is a string and not a boolean. Hence your is not True and is not False tests, although they have well-defined meaning, that meaning is not the meaning that you intend. You need to compare HEADER against string values.
So you would need, for example, code like this:
if HEADER.lower() == 'true':
I used tolower() to effect case-insensitive comparison. You may also want to strip off white space:
if HEADER.strip().lower() == 'true':
I'm sure you can fill in the test against false yourself.
Even if you did have a boolean, you should not use code like is not True or is False. You should test for truth with:
if somebool:
or
if not somebool:
because it is much more readable.
HEADER is a string, not a boolean. This will cause the is check to fail. Your comparison runs like this:
>>> "True" is not True
True
>>> "True" is not False
True
Note that a comparison with == will also fail:
>>> "True" == True
False
>>> "True" == False
False
Try comparing the value as a string:
if HEADER.tolower() == 'true':
#do something
elif HEADER.tolower() == 'false:
#do something else

Categories