2016-09-18 659 views
-4
def eCount (s): 

    """Count the e's in a string, using for loop. 

    Params: s (string) 
    Returns: (int) #e in s, either lowercase or uppercase 
    """ 

    # INSERT YOUR CODE HERE, replacing 'pass' 

教授要求不要改變上面的任何內容。 我試圖做到:在python中使用for循環來計算字符串中的字符(包括大寫和小寫)

count = 0 
for e in s: 
    count +=1 
return count 

它提供:

(executing lines 1 to 17 of "e_count_103.py") 

15 
+2

'爲電子商務在S:'沒有做什麼,你認爲它。嘗試在每次迭代中打印「e」的值。另外,你還沒有真正問過問題。 – roganjosh

+0

'return s.lower()。count('e')'或'return s.upper()。count('E')'試試這個 –

回答

2

你可以嘗試count()像: return s.lower().count('e')

在Python 3:

def eCount(s): 
    return s.lower().count('e') 
s = "helloEeeeeE" 
print(eCount(s)) 

輸出:

7 

您可以小寫字符串或大寫字母由您決定。 (對於大寫,您可以使用s.upper().count('E'))。詳細信息請參閱String count() tutorial

或者,如果你想使用for循環再試試這個(在Python 3):

def eCount(s): 
    count = 0 
    s = s.lower() 
    for i in s: 
     if i == 'e': 
      count+=1 
    return count 
s = "helloEeeeeE" 
print(eCount(s)) 

它提供了相同的輸出:

7 

注:e您在使用你的代碼在這個聲明中:for e in s:不是字符'e'而是變量e所以它迭代字符數s在 的字符串中,每次遞增count變量。

您還可以使用列表理解

def eCount(s): 
    return sum([1 for i in s if i == 'e' or i == 'E']) 
s = "helloEeeeeE" 
print(eCount(s)) 

有關列表理解的細節,你可以檢查此Python - emulate sum() using list comprehension

+1

你爲什麼要回答某人的任務?另外,如果OP正在爲's in s'掙扎,那麼她無論如何都不會放棄提交代碼 – roganjosh

+0

爲什麼你會在這裏建議基於索引的循環?啊。 –

+0

@ Stefan Pochmann對不起,我更新了答案。我猜C++的習慣。謝謝。 –

1

使用for循環:

def eCount(s): 
    count = 0 
    for c in s: 
     if c in ('e', 'E'): 
      count += 1 
    return count 
相關問題