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

วิธีเช็คว่า String มีเฉพาะ Characters ที่กำหนดใน Python

1. ใช้ Sets

from sets import Set
allowed_chars = Set('1234')
validationString = '121'
if Set(validationString).issubset(allowed_chars):
    print(True)
else:
    print(False)

ผลลัพธ์

True

2. ใช้ Regex ^[1234]+$

>> import re
>>> bool(re.match('^[1234]+$', '123abc'))
False
>>> bool(re.match('^[1234]+$', '123'))
True

หมายเหตุ: Regex ต้อง escape ตัวอักษรพิเศษ ใช้ re.escape()