Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 504
AdeleGoldberg Avatar asked Jan 24 '23 15:01

AdeleGoldberg


1 Answers

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.

like image 167
Jon Kiparsky Avatar answered Jan 29 '23 23:01

Jon Kiparsky