[英]Issue detecting if an input contains both letters and numbers
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+).+))
Idea from https://stackoverflow.com/a/24656216/10875953来自https://stackoverflow.com/a/24656216/10875953的想法
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.
对于每个 char 运行所有测试,直到一个匹配。 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.您的方法朝着正确的方向发展,但是
if
语句的缩进和您的逻辑有点可疑。 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 Output
1234 is not mixed
12ab is mixed charcters
abcd is not mixed
1234abcd is mixed charcters
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.