When running this code below with input that includes both letters and numbers it prints not...
# test for both numbers and letters
def multi_test(analysis_input):
alpha_test = False
number_test = False
if analysis_input.isalpha():
alpha_test = True
if analysis_input.isnumeric():
number_test = True
if alpha_test and number_test:
print(analysis_input,'is multiple charcters')
else:
print('not')
analysis_input = input('enter your string arguement')
multi_test(analysis_input)
You need to check for each character:
def multi_test(analysis_input):
alpha_test = False
number_test = False
for char in analysis_input:
if char.isalpha():
alpha_test = True
if char.isnumeric():
number_test = True
if alpha_test and number_test:
print(analysis_input,'is multiple charcters')
else:
print('not')
analysis_input = input('enter your string arguement')
multi_test(analysis_input)
EDIT: a perhaps faster and nicer method is using regex
^(?=.*[a-zA-Z]+)(?=.*\d+).+
# pseudo code, i'm not sure if this code works but its something like this
return bool(re.match(analysis_input, ^(?=.*[a-zA-Z]+)(?=.*\d+).+))
For fun, here is an alternative strategy. Set up a list of the tests. For each char run all tests until one is a match. When one test is positive, remove it from the list of tests. When the list is empty, you've matched all requirements and can stop.
This method will have the advantage of only running the necessary tests and stopping as soon as you matched all tests once:
def multi_test(s):
tests = [str.isalpha, str.isdigit]
for char in s: # for each character
for i,test in enumerate(tests):
if test(char): # if test is positive
tests.pop(i) # remove it from the list of tests
break
if len(tests) == 0: # if there is no test remaining
return True # this is a success, we're done
return False
multi_test('abc1')
# True
You don't need to check every character. Your approach went in the right direction, but the indentation of the if
statements and your logic was a bit questionable. After removing all the redundant parts you get
def multi_test(analysis_input):
if analysis_input.isnumeric() or analysis_input.isalpha():
print(analysis_input,'is not mixed')
else:
print(analysis_input,'is mixed charcters')
Some test cases
for i in ['1234','12ab', 'abcd','1234abcd']:
multi_test(i)
Output
1234 is not mixed
12ab is mixed charcters
abcd is not mixed
1234abcd is mixed charcters
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.