-1

I am building a program that gets a password as a string and checks its strength by a couple of factors. I want to check if the entered string contains a special character (like %,$,# etc.) but so far I couldn't able to figure it out. What is the best way to do so?

Edit: I am not searching for a specific character. I need to search the string to find if it has some kind of a non-letter, non-digit character.

Edit 2 : I want to do it without a loop.

MichaelFel123
  • 53
  • 1
  • 1
  • 6

3 Answers3

5

You can possibly use regex!

>>> import re
>>> s='Hello123#'
>>> re.findall('[^A-Za-z0-9]',s)
['#']
>>> if re.findall('[^A-Za-z0-9]',s):print True
... 
True

Happy Coding!

Hope it helps!

Keerthana Prabhakaran
  • 3,766
  • 1
  • 13
  • 23
1

As you stated you don't want to use a loop, and probably never worked with regexes, how about a list comprehension?

import string

all_normal_characters = string.ascii_letters + string.digits

def is_special(character):
  return character not in all_normal_characters

special_characters = [character for character in password if is_special(character)]

Let me know if this works, or if you need more help!

rmeertens
  • 4,383
  • 3
  • 17
  • 42
-2

You will have to put his into a for loop to check for special character and I think you need to make a list with them all in and then test it like that but this is the basic code you need! Replace the print bit with whatever else you need to do!

password = "VerySecurePassw0rd"
if "%" in password:
    print( "Your Password has a special character in it!")

if "%" not in password:
    print ("Your Password does not have a special character in it!")

EDIT:

Or you could use "else" above

Without using a loop I'm not sure however you could use "elif" but it's not very efficient

password = "VerySecurePassw0rd"

if "%" in password:
    print ("Your Password has a special character in it!")
elif "$" in password:
    print( "Your Password has a special character in it!")
elif "#" in password:
    print ("Your Password has a special character in it!")

You could also try this:

if "%" and "$" in password:
    print("Your Password has a 2 special characters in it!")

I think that should work

Matt
  • 131
  • 3
  • 10