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

Python – กรองสตริงในช่วง ASCII


เมื่อต้องการกรองสตริงที่อยู่ในช่วง ASCII จะใช้เมธอด ord() สำหรับการแทนค่า Unicode และตัวดำเนินการ all()

ตัวอย่าง

my_string = "Hope you are well"
print("The string is :")
print(my_string)
my_result = all(ord(c) < 128 for c in my_string)
if(my_result == True):
    print("The string contains ASCII characters")
else:
    print("The string doesn't contain all ASCII characters")

ผลลัพธ์

The string is : Hope you are well
The string contains ASCII characters

คำอธิบาย

  • กำหนดสตริงและแสดงผลบนคอนโซล

  • เรียกเมธอด ord() กับทุกตัวอักษรในสตริง และตรวจสอบว่าค่า Unicode น้อยกว่า 128 หรือไม่

  • หากทุกตัวอักษรมีค่า Unicode น้อยกว่า 128 จะได้ค่า Boolean True

  • หลังวนลูปเสร็จ ตรวจสอบค่า Boolean นี้

  • แสดงข้อความที่เกี่ยวข้องตามค่าที่ได้