5

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

AdeleGoldberg
  • 1,289
  • 3
  • 12
  • 28
  • 4
    'abc' is alphanumeric. you probably want to check 2 conditions at once (has at least 1 number AND has at least 1 letter) – byxor Nov 16 '20 at 17:23
  • 1
    Does this answer your question? [Python: Regular expression to match alpha-numeric not working?](https://stackoverflow.com/questions/4722998/python-regular-expression-to-match-alpha-numeric-not-working) – Tom Wojcik Nov 16 '20 at 17:24
  • 1
    yes @user12386945. It MUST have alphabets and numerals. – AdeleGoldberg Nov 16 '20 at 17:26

3 Answers3

7

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:

def containsLetterAndNumber(input):
    return any(x.isalpha() for x in input) and any(x.isnumeric() for x in input)
Aplet123
  • 33,825
  • 1
  • 29
  • 55
7

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.

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
-2

You can also use regexes bool(re.match('^[a-zA-Z0-9]+$', 'string'))