简体   繁体   中英

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:

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

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.

您还可以使用正则表达式 bool(re.match('^[a-zA-Z0-9]+$', 'string'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM