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
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
Therefore, if input
contains any non-alphanumeric characters, the first check is false. 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()
. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With