新聞中心
創(chuàng)新互聯(lián)Python教程:

成都創(chuàng)新互聯(lián)長期為上1000+客戶提供的網(wǎng)站建設服務,團隊從業(yè)經(jīng)驗10年,關(guān)注不同地域、不同群體,并針對不同對象提供差異化的產(chǎn)品和服務;打造開放共贏平臺,與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為原州企業(yè)提供專業(yè)的網(wǎng)站制作、網(wǎng)站設計,原州網(wǎng)站改版等技術(shù)服務。擁有十年豐富建站經(jīng)驗和眾多成功案例,為您定制開發(fā)。
寫一個 Python 程序來計算一個字符串中的總字數(shù),并給出一個實例。
計算字符串中總字數(shù)的 Python 程序示例 1
這個 python 程序允許用戶輸入一個字符串(或字符數(shù)組)。接下來,它使用 For 循環(huán)計算該字符串中出現(xiàn)的單詞總數(shù)。這里,我們使用 Python For 循環(huán)來迭代字符串中的每個字符。在 For 循環(huán)中,我們使用 If 語句來檢查是否有空格。如果它找到了空白,那么總字數(shù)就會增加。
# Python program to Count Total Number of Words in a String
str1 = input("Please Enter your Own String : ")
total = 1
for i in range(len(str1)):
if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'):
total = total + 1
print("Total Number of Words in this String = ", total)
計算字符串字數(shù)的 Python 程序示例 2
這個 python 程序的一個字符串的總字數(shù)同上。然而,我們只是將換成了而環(huán)。
# Python program to Count Total Number of Words in a String
str1 = input("Please Enter your Own String : ")
total = 1
i = 0
while(i < len(str1)):
if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'):
total = total + 1
i = i + 1
print("Total Number of Words in this String = ", total)Python 使用 while 循環(huán)輸出對字符串中的單詞進行計數(shù)
Please Enter your Own String : Tutorial Gateway
Total Number of Words in this String = 2
計算字符串總字數(shù)的 Python 程序示例 3
該 Python 計數(shù)字符串中的總字數(shù)與第一個示例相同。但是,這一次,我們使用了函數(shù)概念來分離 Python 邏輯。
# Python program to Count Total Number of Words in a String
def Count_Total_Words(str1):
total = 1
for i in range(len(str1)):
if(str1[i] == ' ' or str1 == '\n' or str1 == '\t'):
total = total + 1
return total
string = input("Please Enter your Own String : ")
leng = Count_Total_Words(string)
print("Total Number of Words in this String = ", leng)Python 使用函數(shù)輸出對字符串中的單詞進行計數(shù)
Please Enter your Own String : Python Hello World Program
Total Number of Words in this String = 4 網(wǎng)站欄目:Python程序:計算字符串中總字數(shù)
網(wǎng)頁路徑:http://www.dlmjj.cn/article/djjighe.html


咨詢
建站咨詢
