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。
迭代字串,並遞增字元變數。
如果遇到空格,則單詞數也遞增。
這些值顯示在控制檯上。
廣告
資料結構
計算機網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP