โจทย์: กำหนดประโยค นับจำนวนคำ มี 2 วิธี
วิธี 1: ใช้ split()
test_string = "Tutorials point"
res = len(test_string.split())
print("The number of words in string are:", str(res))
ผลลัพธ์
The number of words in string are: 2
วิธี 2: ใช้ strip() และ isalpha()
import string
test_string = "Tutorials point"
res = sum([i.strip(string.punctuation).isalpha() for i in test_string.split()])
print("The number of words in string are:", str(res))
ผลลัพธ์
The number of words in string are: 2
สรุป
เรียนรู้ 2 วิธีนับคำในประโยค: split() และ strip()+isalpha()