Python 程式,用於計算字串中存在的單詞數量和字元數量


當需要計算字串中存在的單詞數量和字元數量時,

以下是對此的演示

示例

 即時演示

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。

  • 迭代字串,並遞增字元變數。

  • 如果遇到空格,則單詞數也遞增。

  • 這些值顯示在控制檯上。

更新於:16-4-2021

1K+ 次瀏覽

啟動您的 職業生涯

透過完成課程獲取認證

開始學習
廣告
© . All rights reserved.