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

Python – ตรวจสอบความยาวสตริงตามที่กำหนด

เมื่อต้องการตรวจสอบว่าสตริงแต่ละตัวในลิสต์มีความยาวตรงตามที่กำหนดหรือไม่ สามารถใช้ลูป iteration และ len() ได้

ตัวอย่าง

my_list = ["python", 'is', 'fun', 'to', 'learn', 'Will', 'how']
print("The list is :")
print(my_list)
length_list = [6, 2, 3, 2, 5, 4, 3]
my_result = True
for index in range(len(my_list)):
    if len(my_list[index]) != length_list[index]:
        my_result = False
        break
print("The result is :")
if my_result == True:
    print("All the strings are of required lengths")
else:
    print("All the strings are not of required lengths")

ผลลัพธ์

The list is : ['python', 'is', 'fun', 'to', 'learn', 'Will', 'how']
The result is : All the strings are of required lengths

คำอธิบาย

  • กำหนดลิสต์สตริงและลิสต์ความยาวที่คาดหวัง (length_list)

  • ตั้งค่า flag my_result = True

  • วนลูปเปรียบเทียบความยาวแต่ละสตริงกับค่าใน length_list ดัชนีเดียวกัน

  • ถ้ามีคู่ไหนไม่เท่ากัน ตั้ง flag = False และ break

  • แสดงข้อความตามค่า flag