如何在Python中过滤字符串中的字母

2024-03-28 22:00:20 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,所以我想过滤除了a之外的每个字符串,并打印出句子中a个字母的数量:

import string
sentence = "The cat sat on the mat."
for letter in sentence:
      print(letter)

Tags: the字符串importfor数量stringon字母
3条回答

要打印出'a'的编号,只需:

sentence.count('a')

要过滤掉除'a'之外的所有内容,请使用理解:

^{pr2}$

首先,在使用filter函数打印之前,只需删除所有as。然后,使用count()来计算发生次数

filter(lambda x: x != 'a', sentence)
#Out: 'The ct st on the mt.'
sentence.count('a')
#Out: 3

过滤除字母'a'之外的所有内容的另一种方法是使用内置的filter函数

filtered = ''.join(filter(lambda char: char != 'a', word))
print(filtered)

正如已经建议的那样,使用str.count方法来计算字符串中的字符数

^{pr2}$

相关问题 更多 >