试图计算python中的某些字符

时间:2017-10-19 16:04:40

标签: python python-2.7

我希望代码能够计算"!?,,但是当我运行代码时,它会对所有输入的字符进行计数。谁能告诉我哪里搞砸了?

def how_eligible():
    total = 0
    x = ('"','!','?',',')
    y = raw_input('Write your essay here.')
    for y in x:
        if y in x:
            total = total + 1
    print total

3 个答案:

答案 0 :(得分:0)

我会将你的双循环更改为

for c in y:
    if c in x:
        total = total + 1

答案 1 :(得分:0)

想知道..一个Pythonic 1衬里解决方案

x = ('"','!','?',',')
y = input('Write your essay here.')
len([i for i in y if i in x])

答案 2 :(得分:0)

您还可以使用收藏模块中的计数器:

from collections import Counter

in_s = 'abc?c?"!'
need = ['"', '!', '?']

char_count = Counter(in_s)

for c in need:
    print(c, char_count[c])