Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเช็คว่า String มีอย่างน้อย 1 ตัวอักษรและ 1 ตัวเลขใน Python

1. ใช้ Regex lookaheads

>> import re
>>> bool(re.match('^(?=.*[0-9])(?=.*[a-zA-Z])', 'hasAlphanum123'))
True
>>> bool(re.match('^(?=.*[0-9])(?=.*[a-zA-Z])', 'some string'))
False

(?=...) คือ positive lookahead ดูข้างหน้าว่ามี pattern หรือไม่

2. ใช้ Loop + Flags

def validateString(s):
    letter_flag = False
    number_flag = False
    for i in s:
        if i.isalpha():
            letter_flag = True
        if i.isdigit():
            number_flag = True
    return letter_flag and number_flag

print(validateString('hasAlphanum23'))  # True
print(validateString('some string'))    # False