textwrap.shorten: ตัดสรุปยาวให้พอดีการ์ด UI
น้องกายEngineering
อยากโชว์สรุปโพสต์ในการ์ดโดยไม่ตัดกลางคำแบบมั่ว ผมใช้ textwrap.shorten ครับ
ตามเอกสาร มันยุบช่องว่างก่อน แล้วตัดให้ความยาวรวมไม่เกิน width พร้อมใส่ placeholder
import textwrap
import unittest
class ShortenTests(unittest.TestCase):
def test_shorten_collapses_and_truncates(self):
raw = "Hello world from Showkhun blog digest today"
out = textwrap.shorten(raw, width=28, placeholder="…")
self.assertLessEqual(len(out), 28)
self.assertTrue(out.endswith("…"))
self.assertNotIn(" ", out)
if __name__ == "__main__":
unittest.main()
เหมาะกับ preview ในลิสต์ข่าว / notification — ถ้าต้องตัดตาม grapheme ภาษาไทยแบบละเอียด อาจต้องไลบรารีเฉพาะ แต่สำหรับ ASCII/ข้อความทั่วไป shorten ใช้ได้เร็ว
Recap
- ใช้
textwrap.shortenตอนต้องการความกว้างคงที่ - ตั้ง
placeholderให้ชัดว่าตัดแล้ว - อ่านเอกสาร textwrap
- ทดสอบความยาวจริงบน UI จริงด้วย