2016-11-23 118 views
0

所以,我是一個編程初學者。我正在嘗試創建一個用戶可以輸入句子的程序,程序會告訴用戶該句子中有多少個字母。Python編程字符串處理函數

counter=0 

wrd=raw_input("Please enter a short sentence.") 

if wrd.isalpha(): 
counter=counter+1 
print "You have" + str(counter) +"in your sentence." 

當我輸入這個時,我的輸出是空白的。這個計劃中我的錯誤是什麼?

+0

你有沒有縮進'計數器=計數器+ 1'我想。除此之外,你並不完全使用循環 – martianwars

+0

你可以使用'len()'嗎?這是做你所描述的最簡單和最快的方法。當然,你仍然需要從你的句子中濾除所有的非字母。 –

回答

0

首先爲@kalpesh提到,聲明counter=counter+1應當縮進。

其次,您需要迭代輸入的整個字符串,然後計算字符數或任何您需要的邏輯。

counter=0 

wrd=raw_input("Please enter a short sentence.") 

for i in wrd: 
    if i.isalpha(): 
     counter = counter+1 

print "You have " + str(counter) +"in your sentence." 

一旦你開始學習更多,那麼你可以使用下面的代碼,

counter=[] 
count = 0 
wrd=raw_input("Please enter a short sentence.") 

counter = [len(i) for i in wrd.split() if i.isalpha()] 

print "You have " + str(sum(counter)) +"in your sentence." 

我只是拆分單詞,然後檢查它是否是字母或不使用列表解析來遍歷在輸入的字符串上。

0

wrd.isalpha()返回一個布爾值(true或false)。所以如果函數返回true,counter = counter + 1將會被調用一次(並且只會被調用一次)。您需要遍歷每個字母的每個字母,並調用isalpha()。

1

您需要在if塊內縮進代碼。在你提供的代碼中,你忘記了縮進counter = counter + 1

您錯過了wrd所有字符的循環。試試這個,

所有的
counter = 0 
wrd = raw_input("Please enter a short sentence.") 
# Iterate over every character in string 
for letter in wrd: 
    # Check if the letter is an alphabet 
    if letter.isalpha(): 
    # Increment counter only in this condition 
    counter += 1 

print "You have " + str(counter) + " in your sentence." 
0

您可以使用replace()從句子中刪除空格,然後使用len()來獲取句子中有多少個字符。

例如:

sentence = input("Type in a sentence: ") # Ask the user to input a sentence 
sentence = sentence.replace(" ", "") # Replace the spaces in the sentence with nothing 
print("Your sentence is " + str(len(sentence)) + " characters long") # Use len() to print out number of letters in the sentence