How to test if a character in a string is a number? - python

I'm trying to make a program that tests the strength of a password. Right now, everything else works, however the numbers doesn't. I can't test whether a string is a number without it not returning the last print statement. I probably haven't explained it well, but how can I make it so that it tests if a characer in a string is a number?
error_list = ['']
errors = ''
password = str(input('Enter in your password to test: '))
for char in password:
if type(char) == int:
safe_unsafe.append('y')
else:
safe_unsafe.append('n')
if 'y' in safe_unsafe:
pass
else:
errors = errors + 'No instance of a number was found.\n'
error_list.append('number')
safe_unsafe.clear()
print(errors)

You are looking for isdigit() API
https://docs.python.org/3.8/library/stdtypes.html#str.isdigit
Example
str = "1"
str.isdigit() #this return True
"a".isdigit() #return False
Updates in your code
error_list = ['']
errors = ''
password = str(input('Enter in your password to test: '))
for char in password:
if char.isdigit(): #changed line
safe_unsafe.append('y')
else:
safe_unsafe.append('n')
if 'y' in safe_unsafe:
pass
else:
errors = errors + 'No instance of a number was found.\n'
error_list.append('number')
safe_unsafe.clear()
print(errors)

Related

How do I check if an input value is a valid string?

So I'm making a game of hangman and it starts with a "BotMaster" entering a string and then how many guesses that player will have to try and guess the string. I only just started and I'm trying to write a function that will check if what the BotMaster put is a valid string. A valid string would be a string that is only letters, no symbols, numbers, or extra spaces. I already have the functions that will remove extra spaces, and non-alpha inputs (So it takes out periods, extra spaces and such) and a function that makes it all lower case, but my function breaks if I enter a number an empty string. How should I add these?
#Imports (this is for later code I haven't written)
import os,time,random
#Removes extra spaces from the function
def space_cull(the_str):
result = the_str
result = result.strip()
result =" ".join(result.split())
the_str = result
return the_str
#Makes the string lowercase
def make_lower(the_str):
the_str = the_str.lower()
return the_str
#Checks if everything in the string are Alpha Inputs
def check_alpha(the_str):
the_str =''.join([char for char in the_str if char.isalnum()])
return the_str
#Ask Botmaster the string they want
def ask_bot():
while True:
bot_str = input('Enter a string for the player to guess: ')
bot_str = space_cull(bot_str)
bot_str = make_lower(bot_str)
bot_str = check_alpha(bot_str)
if bot_str == '':
print('That is not a correct string, try again')
True
return bot_str
ask_bot()
I added the ask_bot() part so I can test the function faster
This is what happens:
Enter a string for the player to guess: 1
#nothing
#Tested again:
Enter a string for the player to guess: ''
That is not a correct string, try again.
#But then exits the loop, which I don't want it to, if the string is wrong I want it to ask them again.
#Tested Again
Enter a string for the player to guess: 'Katze'
#Nothing, which is actually good this time
How do I fix this?
Your while loop will always terminate in the function as it is written.
def ask_bot():
while True:
bot_str = input('Enter a string for the player to guess: ')
bot_str = space_cull(bot_str)
bot_str = make_lower(bot_str)
bot_str = check_alpha(bot_str)
if bot_str == '':
print('That is not a correct string, try again')
True # <- this does nothing
return bot_str # < - this breaks out of the function and the loop
Your code edited to work:
def ask_bot():
while True:
bot_str = input('Enter a string for the player to guess: ')
bot_str = space_cull(bot_str)
bot_str = make_lower(bot_str)
bot_str = check_alpha(bot_str)
if bot_str == '':
print('That is not a correct string, try again')
else: # returns the string if the input is correct
return bot_str # this still breaks out of the function and the loop
# but only if the string has passed the checks
As other answers already mention, you could use str.isalpha() to check that the string is valid, or if you would like to modify the string in place you will need to adjust your check_alpha function like so:
def check_alpha(the_str):
the_str =''.join([char for char in the_str if char.isalpha()])
return the_str
As John Gordon already mentioned the solution is the method "isalpha" of the "str" class.
userInput = input("Your suggestion: ")
if userInput.isalpha():
# do some magic
else:
print("please only type in letters")
You don't need the check_alpha(str) function at all. Modify the ask_bot() as follows.
def ask_bot():
while True:
bot_str = input('Enter a string for the player to guess: ')
bot_str = space_cull(bot_str)
bot_str = make_lower(bot_str)
if not bot_str.isalpha():
if bot_str.isnum():
print("The entered string is a number")
continue
if bot_str == '':
print('That is not a correct string, try again')
continue
continue
break
return bot_str
ask_bot()

check pass boolean function

This is my code which and it asks a user to enter a password string and checks for any repeated elements.The thing is I didn't understand the code and why they set a unique_element to an empty string.And what does unique+=password[i] do,why is i in [] in this brackets?
def check_pass():
password= raw_input('Enter a password:')
unique_element = ''
for i in range (len(password)):
if len(unique_element) == 0:
unique_element += password [i]
else:
not_unique = True
for j in range (len(unique_element)):
if unique_element[j] == password[i]:
not_unique = False
if not_unique:
unique_element += password[i]
return unique_element == password
print check_pass()
Explaining the Code above may be a little tedious. Suffice it to say that if your intention is to check if a given String [password] contains any duplicate character, you might do that without the need for any loops - which (in this case) is likely unnecessary. Here's how:
def pass_has_unique_characters():
# CAPTURE THE ENTERED CHARACTERS
password = input('Enter a password:')
# SETS CANNOT HAVE DUPLICATES SO WE CAST THE STRING (password) TO A SET
st_password = set(password)
# NOW WE CHECK THE LENGTHS OF BOTH: password AND st_password
# IF BOTH HAVE THE SAME LENGTH, THEN THE PASS HAS UNIQUE CHARACTERS,
# RETURN [True] ... OTHERWISE RETURN [False]
return (True if len(st_password) == len(password) else False)
print(pass_has_unique_characters())

Regex password program

I'm working on an exercise problem from the regex chapter in 'Automate the boring stuff with Python' the question and my code is below. I got the regex working in the Python shell and I think its correct but I just can't get it to work within my function so that it returns the correct answer.
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 re
def pwRegex():
print "Please enter a password"
user_pw = raw_input("> ")
#your_pw = str(user_pw)
passGex = re.compile(r'^(?=.*\d)(?=.*[A-Z])\w{8,15}$')
pass_w = passGex.search(user_pw)
if pass_w != '':
print "Well done"
else:
print "Try again"
pwRegex()
the output I get is "Try again" every time even when I'm entering a password that should pass the regex. I tried making the if statement pass_w == True: but then everything that I entered seemed to pass the regex even if incorrect.
Regex searching in python gives back a MatchObject, not a string. If it does not find the required pattern, it will return None. You should check for None, or, more pythonically, check for truthiness
# if pass_w != None: # => less pythonic
if pass_w:
print 'Well done'
else:
print 'Try again'
import re
print('Please set a new password: ')
def strongpassword():
while True:
password = input()
if lowcase.search(password) == None:
print('The entered password doesn\'t have a lower case character')
continue
if upcase.search(password) == None:
print('The entered password doesn\'t have an upper case character')
continue
if digit.search(password) == None:
print('The entered password doesn\'t have a digit')
continue
if space_8.search(password) == None:
print('The entered password should have atleast 8 characters and no space in between')
continue
else:
print('New Password is Valid and Saved')
break
lowcase = re.compile(r'[a-z]') # this regex searches for atleast one lower case alphabet
upcase = re.compile(r'[A-Z]') # this regex searches for atleast one upper case alphabet
digit = re.compile(r'(\d)') # this regex searches for atleast one digit
space_8 = re.compile(r'^[a-zA-Z0-9]{8,}$') # this regex searches for expressions without any space and atleast 8 characters
strongpassword()
I guess, it is not relevant anymore. However, I would like to suggest this:
import re
pasword = re.compile(r'''(
\d+ #have at lest one digit
.* # anything
[A-Z]+ # at least 1 capital
.*
[a-z]+ # at least one lower
.*
)''', re.VERBOSE)
# test
pasword.search('1##A!a').group()
def is_strong_password():
pas = input('Enter a password:')
if len(pas) < 8:
return False
else:
check = pasword.search(''.join(sorted(pas))).group() #sorted is important to be sure that user can write symbols in any order he/she wants
if (not check):
print('Not strong pasword')
return False
else:
print('Strong password')
return True
I was also working on the same exercise, I'm learning python as well. You can search() instead of findall(). i just used it just to test it out.
import re
print('Enter new password')
def strongPW():
while True:
pw = input()
lowercase = [] # lowercase
uppercase = [] # uppercase
digit = [] # number
if len(pw) < 8:
print('your password must have 8 characters or more')
break
# lowercase verification
pwRegex = re.compile(r'[a-z]')
lowercase = pwRegex.search(pw)
if lowercase == []:
print('Your password must have at least one lowercase')
break
# uppercase verification
uppercaseRegex = re.compile(r'[A-Z]')
uppercase = uppercaseRegex.findall(pw)
if uppercase == []:
print('Your password must have at least one uppercase')
break
# digit verification
DigitRegex = re.compile(r'[0-9]')
digit = DigitRegex.findall(pw)
if digit == []:
print('Your password must have at least one digit')
break
else:
print('Your password meets all requirements ')
break
strongPW()

Python 3.x input variable

I want to get user input of a code that has to be 11 numbers long and must not contain any characters. Otherwise the question to enter will be repeated.
code=input("Please enter your code ")
while len((code)) !=11: #here should be something to nullify strings inout :)
code = input("Please enter your code and in numbers only ")
There is definitely a better solution for this, just can't think of any.
This might be what you're after
def validate(s):
for char in s: #iterate through string
if not char.isdigit(): # checks if character is not a number
return False # if it's not a number then return False
return True # if the string passes with no issues return True
def enter_code():
while True: #Will keep running until break is reached
code = input("Please enter your code: ") #get user input
# if the length of input and it passes the validate then print 'Your code is valid'
if len(code) == 11 and validate(code):
print('Your code is valid')
break #break out of loop if valid
# if code fails test then print 'Your code is invalid' and return to start of while loop
print('Your code is invalid')
if __name__ == '__main__':
enter_code()

Python. figuring out how to input a correct phone number

So I'm new to python and I'm writing a program that accepts a phone number in the format XXX-XXX-XXXX and changes any letters to their corresponding numbers. I need to check the entry and make sure it's in the correct format, and if its not, allow it to be reentered. I'm having a hard time getting it to prompt me for a new number, and even when that works sometimes, it will still translate the original, wrong phone number.
This is my code so far:
def main():
phone_number= input('Please enter a phone number in the format XXX-XXX-XXXX: ')
validNumber(phone_number)
translateNumber(phone_number)
def validNumber(phone_number):
for i,c in enumerate(phone_number):
if i in [3,7]:
if c != '-':
phone_number=input('Please enter a valid phone number: ')
return False
elif not c.isalnum():
phone_number=input('Please enter a valid phone number: ')
return False
return True
def translateNumber(phone_number):
s=""
for char in phone_number:
if char is '1':
x1='1'
s= s + x1
elif char is '-':
x2='-'
s= s + x2
elif char in 'ABCabc':
x3='2'
s= s + x3
.....etc this part isn't important
You probably want to use a while loop to force the user to input a valid number. Something like:
def main():
phone_number = ""
while not validNumber(phone_number):
phone_number = input('Please enter a phone number in the format XXX-XXX-XXXX: ')
translateNumber(phone_number)
(You may need to replace input with raw_input if you're using Python 2.7,)
Here is a full, working solution.
import re
from string import maketrans
phone_match = re.compile("^(\w{3}-\w{3}-\w{4})$")
def validPhone(number):
match = phone_match.match(number)
if match:
return match.groups(0)[0]
return None
phone_number = ''
while not validPhone(phone_number):
phone_number = raw_input("Give me your digits!: ")
phone_in = "abcdefghijklmnopqrstuvwxyz"
phone_out = "22233344455566677778889999"
transtab = maketrans(phone_in, phone_out)
print phone_number.lower().translate(transtab)
Examples:
Give me your digits!: 949-POO-PTOO
949-766-7866
Give me your digits!: 555-HOT-KARL
555-468-5275

Categories

Resources