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

วิธีเช็ค String ว่างอย่าง Elegan ใน Python

Empty string เป็น "falsy" ใช้ not string ตรวจสอบได้เลย

ตัวอย่าง

string = ""
if not string:
    print("Empty String!")

ผลลัพธ์

Empty String!

กรณีมี whitespace ต้องการถือว่าว่าง

string = "   "
if not string.strip():
    print("Empty String!")

ผลลัพธ์

Empty String!