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

Python – ตรวจสอบว่า Splits เท่ากันหรือไม่


เมื่อจำเป็นต้องตรวจสอบว่าการแบ่งสตริงเท่ากันหรือไม่ วิธี 'len' วิธี 'list' และตัวดำเนินการ 'set' จะถูกใช้ควบคู่ไปกับเงื่อนไข 'if'

ตัวอย่าง

ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -

my_string = '96%96%96%96%96%96'

print("The string is : " )
print(my_string)

my_split_char = "%"
print("The character on which the string should be split is :")
print(my_split_char)

my_result = len(list(set(my_string.split(my_split_char)))) == 1

print("The resultant list is : ")

if(my_result == True):
   print("All the splits are equal")
else:
   print("All the splits are not equal")

ผลลัพธ์

The string is :
96%96%96%96%96%96
The character on which the string should be split is :
%
The resultant list is :
All the splits are equal

คำอธิบาย

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

  • อักขระตามที่ควรแยกสตริงถูกกำหนด

  • นอกจากนี้ยังแสดงบนคอนโซลอีกด้วย

  • สตริงถูกแบ่งตามอักขระนี้ และถูกแปลงเป็นชุดเพื่อให้ได้องค์ประกอบที่ไม่ซ้ำกัน

  • นี้ถูกแปลงเป็นรายการ

  • ความยาวของมันถูกตรวจสอบให้เท่ากับ 1

  • ถ้าใช่ ค่าบูลีนนี้จะถูกเก็บไว้ในตัวแปร

  • ตามค่าของตัวแปรบูลีนนี้ ข้อความที่เกี่ยวข้องจะแสดงบนคอนโซล