เมื่อจำเป็นต้องคำนวณจำนวนคำและอักขระที่มีอยู่ในสตริง
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน
ตัวอย่าง
my_string = "Hi there, how are you Will ? "
print("The string is :")
print(my_string)
my_chars=0
my_words=1
for i in my_string:
my_chars=my_chars+1
if(i==' '):
my_words=my_words+1
print("The number of words in the string are :")
print(my_words)
print("The number of characters in the string are :")
print(my_chars) ผลลัพธ์
The string is : Hi there, how are you Will ? The number of words in the string are : 8 The number of characters in the string are : 29
คำอธิบาย
-
มีการกำหนดสตริงและแสดงบนคอนโซล
-
จำนวนอักขระถูกกำหนดให้เป็น 0
-
จำนวนคำถูกกำหนดให้เป็น 1
-
สตริงถูกวนซ้ำ และตัวแปรอักขระจะเพิ่มขึ้น
-
หากมีการเว้นวรรค จำนวนคำก็จะเพิ่มขึ้นด้วย
-
ค่าเหล่านี้จะแสดงบนคอนโซล