เมธอด str.isprintable() ใช้ตรวจสอบว่า ทุกตัวอักษรในสตริงสามารถพิมพ์/แสดงผลได้หรือไม่ คืนค่า True ถ้าทุกตัวอักษรเป็น Printable Characters หรือสตริงว่างเปล่า คืนค่า False ถ้ามีตัวอักษร Non-printable อย่างน้อย 1 ตัว
Printable Characters คืออะไร?
ตัวอักษรที่ "พิมพ์ได้" หมายถึง ตัวอักษรที่มีการแสดงผลที่มองเห็นได้ ไม่รวม Control Characters เช่น:
- ✅ ตัวอักษร (a-z, A-Z), ตัวเลข (0-9)
- ✅ สัญลักษณ์ (!@#$%^&*()_+-=[]{}|;':",./<>?)
- ✅ Space (ช่องว่าง)
- ❌
\n(Newline),\t(Tab),\r(Carriage Return) - ❌
\x00-\x1f(Control Characters),\x7f(DEL) - ❌ Zero-width characters, Non-breaking space บางประเภท
ไวยากรณ์
str.isprintable() # ไม่รับพารามิเตอร์
ตัวอย่างการใช้งาน
1. สตริงทั่วไป
print('Tutorialspoint'.isprintable()) # True
print('Hello World!'.isprintable()) # True
print('12345'.isprintable()) # True
print(''.isprintable()) # True (สตริงว่าง)
2. มี Control Characters
print('Tutorials\npoint'.isprintable()) # False (\n)
print('Tutorials\tpoint'.isprintable()) # False (\t)
print('Line1\r\nLine2'.isprintable()) # False (\r\n)
print('Hello\x00World'.isprintable()) # False (NULL char)
3. Special Cases
print(' '.isprintable()) # True (Space)
print('\u00a0'.isprintable()) # True (Non-breaking space)
print('\u200b'.isprintable()) # False (Zero-width space)
การประยุกต์ใช้งานจริง
1. ทำความสะอาดข้อมูล (Data Cleaning)
def clean_string(s, replacement=''):
"""แทนที่ Non-printable characters"""
return ''.join(c if c.isprintable() else replacement for c in s)
# ตัวอย่าง
dirty = "Hello\x00World\n\tGoodbye\x1f!"
clean = clean_string(dirty, '?')
print(repr(clean)) # 'Hello?World??Goodbye?!'
2. ตรวจสอบ Input Validation
def validate_input(user_input):
if not user_input.isprintable():
raise ValueError("Input contains non-printable characters")
return user_input
try:
validate_input("Normal text") # OK
validate_input("Bad\x00input") # Raises ValueError
except ValueError as e:
print(e)
3. แสดงเฉพาะตัวอักษรที่พิมพ์ได้
text = "Hello\nWorld\t!" printable_only = ''.join(c for c in text if c.isprintable()) print(repr(printable_only)) # 'HelloWorld!'
4. Debug: หาตำแหน่ง Non-printable Characters
def find_non_printable(s):
for i, c in enumerate(s):
if not c.isprintable():
print(f"Position {i}: {repr(c)} (U+{ord(c):04X})")
find_non_printable("Hello\nWorld\t!")
# Position 5: '\n' (U+000A)
# Position 11: '\t' (U+0009)
ความแตกต่าง: isprintable() vs isalnum() vs isspace()
| เมธอด | True สำหรับ | False สำหรับ |
|---|---|---|
isprintable() | Letters, Digits, Symbols, Space | Control chars (\n, \t, etc.) |
isalnum() | Letters, Digits เท่านั้น | Symbols, Space, Control chars |
isspace() | Whitespace เท่านั้น (\n, \t, space) | Letters, Digits, Symbols |
สรุป
isprintable() เป็นเครื่องมือที่มีประโยชน์สำหรับ Data Validation, Sanitization, และ Debugging ช่วยป้องกันปัญหาการแสดงผลผิดพลาด บันทึก Log ผิดปกติ หรือ Security Issues จาก Control Characters ที่ซ่อนอยู่ในข้อมูลนำเข้า