如何检查某个字符串(例如“ ababac”)出现的次数是否超过给定字符? (例如a = 3,b = 2)

时间:2019-01-04 12:15:22

标签: python python-3.x

我很难找到的是,您不能在布尔逻辑检查中嵌套“ [i] for i in [list]”,并且不想列出所有26个字符

3 个答案:

答案 0 :(得分:0)

例如,您可以使用"aabc".count('a')为您提供aaabc中出现的次数。在此示例中,它给出了2

以此为基础,您可以实施一些简单的代码来检查每个字母的出现次数,如下所示:

import string

s = 'ababac'

for letter in string.ascii_lowercase:
    print("%s appears %s times" % (letter, s.count(letter)))

哪个产生输出:

a appears 3 times
b appears 2 times
c appears 1 times
d appears 0 times
e appears 0 times
f appears 0 times
g appears 0 times
...

注意:您不必列出字母表中的所有26个字符,因为string.ascii_lowercase可以满足您的要求。请注意,还有string.ascii_uppercase,依此类推。详细信息:https://docs.python.org/3/library/string.html

有关str.count(sub[, start[, end]])的更多信息:https://docs.python.org/3/library/stdtypes.html#str.count

collections.Counter也可以为字符串中的所有字母创建字典。使用此方法,您可以这样重写上面的代码:

import string
from collections import Counter

counts=Counter('ababac')
# counts = {'a': 3, 'b': 2, 'c': 1}

for letter in string.ascii_lowercase:
    if letter in counts:
        print("%s appears %s times" % (letter, counts[letter]))
    else:
        print("%s doesn't appear" % letter)

输出:

a appears 3 times
b appears 2 times
c appears 1 times
d doesn't appear
e doesn't appear
f doesn't appear
g doesn't appear
...

编辑NB:

print("%s appears %s times" % (letter, s.count(letter)))

也可以写成:

print("{} appears {} times".format(letter, s.count(letter)))

使用较新的str.format界面。详细信息:https://docs.python.org/3/library/stdtypes.html#str.format

答案 1 :(得分:0)

使用defualtdict可以做到这一点。

from collections import defaultdict
def fun():
    return 0

dic=defaultdict(fun)

string ='ababa'

for i in string:
    dic[i]+=1

for i in dic:
    print(i,dic[i])

输出:

 a 3 
 b 2 

答案 2 :(得分:0)

您可以使用以下代码获取给定字符串中每个可用的字符数

def count_dict(mystring):
    d = {}
# count occurances of character
    for w in mystring: 
        d[w] = mystring.count(w)
# print the result
    for k in sorted(d):
        print (k + ': ' + str(d[k]))

mystring='qwertyqweryyyy'
count_dict(mystring)

您可以找到实时演示here