[英]How to check if a string is strictly contains both letters and numbers
How to check if a string is strictly contains both letters and numbers?如何检查字符串是否严格包含字母和数字?
Following does not suffice?跟随还不够?
def containsLettersAndNumber(input):
if input.isalnum():
return True
else:
return False
isAlnum = containsLettersAndNumber('abc') # Should return false
isAlnum = containsLettersAndNumber('123') # Should return false
isAlnum = containsLettersAndNumber('abc123') # Should return true
isAlnum = containsLettersAndNumber('abc123$#') # Should return true
Please note that It MUST contain both letters and numerals请注意,它必须同时包含字母和数字
You can loop through and keep track of if you've found a letter and if you've found a number:您可以循环并跟踪您是否找到了一个字母以及是否找到了一个数字:
def containsLetterAndNumber(input):
has_letter = False
has_number = False
for x in input:
if x.isalpha():
has_letter = True
elif x.isnumeric():
has_number = True
if has_letter and has_number:
return True
return False
Alternatively, a more pythonic but slower way:或者,一种更pythonic但速度较慢的方式:
def containsLetterAndNumber(input):
return any(x.isalpha() for x in input) and any(x.isnumeric() for x in input)
Simplest approach using only string methods:仅使用字符串方法的最简单方法:
def containsLetterAndNumber(input):
return input.isalnum() and not input.isalpha() and not input.isdigit()
input.isalnum
returns true iff all characters in S are alphanumeric, input.isalpha
returns false if input contains any non-alpha characters, and input.isdigit
return false if input contains any non-digit characters input.isalnum
返回true,当且仅当S中的所有字符是字母数字, input.isalpha
返回false如果输入包含非字母字符,并input.isdigit
返回false,如果输入包含任何非数字字符
Therefore, if input
contains any non-alphanumeric characters, the first check is false.因此,如果
input
包含任何非字母数字字符,则第一次检查为假。 If not input.isalpha()
then we know that input
contains at least one non-alpha character - which must be a digit because we've checked input.isalnum()
.如果
not input.isalpha()
那么我们知道input
至少包含一个非字母字符——它必须是一个数字,因为我们已经检查了input.isalnum()
。 Similarly, if not input.isdigit()
is True then we know that input
contains at least one non-digit character, which must be an alphabetic character.同样,如果
not input.isdigit()
不是 True 则我们知道input
至少包含一个非数字字符,该字符必须是字母字符。
您还可以使用正则表达式 bool(re.match('^[a-zA-Z0-9]+$', 'string'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.