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

โปรแกรม Python นับจำนวนคำและตัวอักษรในสตริง


นับจำนวนคำและตัวอักษรในสตริง โดยนับตัวอักษรทุกตัว และนับคำจากจำนวนช่องว่าง

ตัวอย่างโค้ด

my_string = "Hi there, how are you Will ?"
print("The string is:", my_string)

chars = 0
words = 1  # เริ่มที่ 1 เพราะคำแรกไม่มี space นำหน้า

for ch in my_string:
    chars += 1
    if ch == ' ':
        words += 1

print("Number of words:", words)
print("Number of characters:", chars)

ผลลัพธ์

The string is: Hi there, how are you Will ?
Number of words: 8
Number of characters: 29

คำอธิบาย

  • chars นับทุกตัวอักษรรวม space และ punctuation

  • words เริ่มที่ 1 (คำแรก) เพิ่มทุกครั้งเจอ space

  • วิธีนี้สมมติคำคั่นด้วย space เดียว (หลาย space ติดกันจะนับผิด)

  • วิธีมาตรฐาน: len(my_string.split()) สำหรับคำ, len(my_string) สำหรับตัวอักษร