行,所以我想每個字符串除了a
過濾,並打印出的a
信件的數量,在句子:如何篩選字母串在Python
import string
sentence = "The cat sat on the mat."
for letter in sentence:
print(letter)
行,所以我想每個字符串除了a
過濾,並打印出的a
信件的數量,在句子:如何篩選字母串在Python
import string
sentence = "The cat sat on the mat."
for letter in sentence:
print(letter)
要打印出的'a'
數量,只是:
sentence.count('a')
要過濾掉一切,但'a'
,用理解:
filtered = ''.join(i for i in sentence if i != 'a')
print(filtered)
謝謝你的工作 –
要顯示字符串中出現'a'的數字,您可以使用@Burhan提到的字符串中的簡單計數函數。
sentence.count('a')
定義一個函數來計算字符串中'a'的數量。儘管如此,你應該避免這種情況,但知道如何計算字符串中的特定字符或單詞是很好的。
def count_specific_character(sentence):
count = 0
for character in sentence:
if character == 'a':
count += 1
return count
「總是很好有用戶定義的功能」 - 實際上,最好使用內置函數或內置類型方法。他們通常更快,更強大。 – TigerhawkT3
感謝您點擊此@ TigerhawkT3!我編輯它! – pythondetective
過濾一切,但信'a'
另一種方法是使用內置的filter
功能
filtered = ''.join(filter(lambda char: char != 'a', word))
print(filtered)
而作爲已經建議使用str.count
方法計算字符串中的字符數
word.count('a')
首先簡單地刪除所有a
s打印前使用filter
函數。然後,使用count()
來計算出現次數
filter(lambda x: x != 'a', sentence)
#Out: 'The ct st on the mt.'
sentence.count('a')
#Out: 3
您能否顯示樣本輸入和預期輸出。 SO問題沒有一個解決您的問題。 – The6thSense
到目前爲止你做了什麼?你有什麼嘗試?沒有SO用戶會爲你寫代碼! –