This question already has answers here:
How to check a string for specific characters?
(8 answers)
How to check a string for a special character?
(5 answers)
Closed 5 years ago.
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.
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!
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!
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
Related
This question already has answers here:
Checking whether a string starts with XXXX
(5 answers)
Closed 2 years ago.
I'm attempting to make a 'check' to see if a given link matches a certain pattern. Here's what I have so far:
love = input("Enter URL: ")
while True:
if love == 'https://www.youtube.com/watch?v=*':
print("confirm, what is love?")
break
else:
print("NOT A YOUTUBE LINK")
love is supposed to be a youtube link, starting in https://www.youtube.com/watch?v= and ending in 11 wildcard characters. How would one do this?
Use the startswith() method.
if love.startswith('https://www.youtube.com/watch?v='):
If you need exactly 11 characters after the =, you could use regex:
import re
love = input("Enter URL: ")
if re.search(r"http://youtube.com/watch\?v=.{11}", love):
print("Valid")
else:
print("Invalid")
The .{11} in the regex pattern means match any character (.) exactly 11 times ({11}).
You don't need a while loop for the if statement like that. If you write it that way, your program will continuously print out "NOT A YOUTUBE LINK" because you have no break for else. If you put a break in your else statement, then there is no use for a while loop, since you stop the program after one try anyway. Also, use startswith() to check for the URL
If you want to use a loop, you can use it this way:
def checkURL(inputURL):
if inputURL.startswith('https://www.youtube.com/watch?v='):
print("confirm, what is love?")
else:
print("NOT A YOUTUBE LINK")
while True:
love = input("Enter URL: ")
if love.lower() != "quit":
checkURL(love)
else:
break
I see some problems with your code:
you don't need the while loop, it will end your computer memory as long it is not a youtube link
You can just check if youtube.com in the string variable.
youtube domains can be **youtube.com`, youtu.be, and maybe some more that I don't know about. I suggest putting all of them in a list and check.
This question already has answers here:
Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters
(42 answers)
Closed 2 years ago.
I'm writing a program which returns a certain message depending on the strength of the inputted password. In order to be labelled as ''strong'', it has to meet certain requirements, which I'm going to list below in the program's documentation :
#! python3
# strongPassword.py
# Strong Password Detection
# Write a function that uses regular expressions to make sure
# the password string it is passed is strong. A strong password
# is defined as one that is at least eight characters long,
# contains both uppercase and lowercase characters, and has
# at least one digit. You may need to test the string against
# multiple regex patterns to validate its strength.
import pyperclip, re
passwordRegex = re.compile(r'''(
^(?=.*[A-Z].*[A-Z]) # at least two capital letters
(?=.*[!##$&*]) # at least one of these special characters
(?=.*[0-9].*[0-9]) # at least two numeric digits
(?=.*[a-z].*[a-z].*[a-z]) # at least three lower case letters
.{10,} # at least 10 total digits
$
)''', re.VERBOSE)
def userInputPasswordCheck():
ppass = input("Enter a potential password: ")
mo = passwordRegex.search(ppass)
if (not mo):
print("Not strong, bling blong")
return False
else:
print("Long, Strong, and down to get the crypto on")
return True
userInputPasswordCheck()
I found this code on Github, but I don't quite understand how it manages to create a regular expression that doesn't list certain parts of the pattern in order.
What my concrete question is, is how am I able to write a regex in a more ''vague'' manner ( only mentioning the requirements, like minimum x number of upper case characters, y number of lower case characters and z number of digits, without highlighting the order in which each part has to occur ).
This particular code seems to use ''?='', which I don't fully understand ( lookahead assertion, matching the particular part of the string only if it's followed by another specific part of the string, I know, I just don't understand how it's utilized in this particular code ).
I'd greatly appreciate any assistance.
Thanks in advance.
Here is how:
from re import search
def userInputPasswordCheck():
pas = input('Input your password: ')
if all([len(pas) > 7, search('[0-9]', pas), search('[a-z]', pas), search('[A-Z]',pas)]):
print("Long, Strong, and down to get the crypto on")
return True
else:
print("Not strong, bling blong")
return False
userInputPasswordCheck()
Output:
Input your password: Hello101
Long, Strong, and down to get the crypto on
I'm new to Python and I have a question.
I am making a simple chatbot and I want it to give answers to questions and things like that.
Here is an example:
def ChatMode():
ChatCommand = raw_input ("- user: ")
if "quit" in ChatCommand :
print "Lucy: See you later."
print ""
UserCommand()
else :
print "Lucy: sorry i don\'t know what you mean."
ChatMode()
For something more advanced I need it to check for 2 strings.
I tried some things like:
def ChatMode() :
ChatCommand = raw_input ("- user: ")
if "quit" + "now" in ChatCommand :
print "Lucy: See you later."
print ""
UserCommand()
else :
print "Lucy: sorry i don\'t know what you mean."
ChatMode()
But that made "quitnow".
I also tried to replace the + with an & but that gave me an error:
TypeError: unsupported operand type(s) for &: 'str' and 'str'
Does anyone have a short code to do this? I don't want 5+ sentences, I want to keep it as short as possible.
Use separate clauses to check if both "quit" and "now" are in the ChatCommand e.g.
if "quit" in ChatCommand and "now" in ChatCommand:
Note that in Python, the logical and operator && is and, and & is the bitwise and.
if "quit" in ChatCommand and "now" in ChatCommand:
Also, as a bit of style, in Python CamelCase is usually reserved for Classes.
Use all():
if all(word in ChatCommand for word in ("quit", "now")):
If you want to avoid matching quit within quite, you can use a regex:
import re
if all(re.search(regex, ChatCommand) for regex in (r"\bquit\b", r"\bnow\b")):
because the \b word boundary anchors only match at the start and end of a word.
I'm trying to create a function to check if the user inputs a number. If the user inputs a number my program should output an error message, if the users enters a string of letters, my program should proceed with program. How can I do this?
I've come up with this so far:
#Checks user input
def CheckInput():
while True:
try:
city=input("Enter name of city: ")
return city
except ValueError:
print ("letters only no numbers")
This function doesn't seem to work. Please help.
You are looking to filter out any responses that include digits in the string. The answers given will do that using a regular expression.
If that's all you want, job done. But you will also accept city names like Ad€×¢® or john#example.com.
Depending on how choosy you want to be, and whether you're just looking to fix this code snippet or to learn the technique that the answers gave you so that you can solve the next problem where you want to reject anything that is not a dollar amount, say),you could try writing a regular expression. This lets you define the characters that you want to match against. You could write a simple one to test if the input string contains a character that is not a letter [^a-zA-Z] (the ^ inside [ ] means any character that is not in the class listed). If that RE matches, you can then reject the string.
Then consider whether the strict rule of "letters only" is good enough? Have you replaced one flawed rule (no digits allowed) with another? What about 'L.A.' as a city name? Or 'Los Angeles'? Maybe you need to allow for spaces and periods. What about hyphens? Try [^a-zA-Z .-] which now includes a space, period and hyphen. The backslash tells the RE engine to treat that hyphen literally unlike the one in "a-z".
Details about writing a regex here:http://docs.python.org/3/howto/regex.html#regex-howto
Details about using the Re module in Python here: http://docs.python.org/3/library/re.html#module-re
import re
def CheckInput():
city = input('Enter name of city: ')
if re.search(r'\d', city):
raise Exception('Invalid input')
You wouldn't be type checking because in Python 3 all text inputs are strings. This checks for a decimal value in the input using regular expressions and raises an exception if one is found.
val = input("Enter name of city:")
try:
int( val )
except ValueError:
return val
else:
print("No numbers please")
Edit: I saw mention that no number should be present in the input at all. This version checks for numbers at any place in the input:
import re
val = input("Enter name of city:")
if re.search( r'\d', val ) is not None:
print("No numbers please")
else:
return val
You can use the type(variable_name) function to retrieve the type.
I'm trying to learn how to program and I'm running into a problem....
I'm trying to figure out how to make sure someone inputs a number instead of a string. Some related answers I found were confusing and some of the code didn't work for me. I think someone posted the try: function, but it didn't work, so maybe I need to import a library?
Here's what I'm trying right now:
Code:
print "Hi there! Please enter a number :)"
numb = raw_input("> ")
if numb != str()
not_a_string = int(next)
else:
print "i said a number, not a string!!!"
if not_a_string > 1000:
print "You typed in a large number!"
else:
print "You typed in a smaller number!"
Also I have another question while I'm asking. How can I make it so it will accept both uppercase and lower case spellings? In my code below, if I were to type in "Go to the mall" but with a lowercase G it would not run the if statement because it only accepts the capital G.
print "What would you like to do: \n Go to the mall \n Get lunch \n Go to sleep"
answer = raw_input("> ")
if answer == "Go to the mall":
print "Awesome! Let's go!"
elif answer == "Get lunch":
print "Great, let's eat!"
elif answer == "Go to sleep":
print "Time to nap!"
else:
print "Not what I had in mind...."
Thanks. ^^
Edit: I'm also using python 2.7 not 3.0
You can do something like this:
while True: #infinite loop
ipt = raw_input(' Enter a number: ')
try:
ipt = int(ipt)
break #got an integer -- break from this infinite loop.
except ValueError: #uh-oh, didn't get an integer, better try again.
print ("integers are numbers ... didn't you know? Try again ...")
To answer your second question, use the .lower() string method:
if answer.lower() == "this is a lower case string":
#do something
You can make your string comparisons really robust if you want to:
if answer.lower().split() == "this is a lower case string".split():
In this case, you'll even match strings like "ThIs IS A lower Case\tString". To get even more liberal in what you accept, you'd need to use a regular expression.
(and all this code will work just fine on python2.x or 3.x -- I usually enclose my print statements in parenthesis to make it work for either version).
EDIT
This code won't quite work on python3.x -- in python3, you need to change raw_input into input to make it work. (Sorry, forgot about that one).
First,you should ask only one question per post.
Q1: use built-in .isdigit()
if(numb.isdigit()):
#do the digit staff
Q2:you can use string.lower(s) to solve the capital issue.
you may try
numb = numb.strip()
if numb.isdigit() or (numb[0] in ('+', '-') and numb[1:].isdigit():
# process numb