Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python计算字符串中的字符数_Python_Python 3.x_String - Fatal编程技术网

使用python计算字符串中的字符数

使用python计算字符串中的字符数,python,python-3.x,string,Python,Python 3.x,String,我被要求在不使用string类的情况下计算用户给定的字符在用户给定的字符串中出现的次数。在python中,计数方法和字典都还没有达到这一点。有没有办法计算角色重复的次数 user_string = "Hello! What a fine day it is today." user_character = "e" count = 0 for a in user_string: if user_string == user_character:

我被要求在不使用string类的情况下计算用户给定的字符在用户给定的字符串中出现的次数。在python中,计数方法和字典都还没有达到这一点。有没有办法计算角色重复的次数

user_string = "Hello! What a fine day it is today."    
user_character = "e"   
count = 0   
for a in user_string:   
     if user_string == user_character:         
     count += 1    
print(count)

我知道上面的代码是错误的,因为它将完整字符串与单个字符进行比较。因此,如果有人能够纠正它并提供一个程序,这将非常有帮助。

修复程序的明显变化是if条件:

count = 0   
for a in user_string:   
    if a == user_character:         
        count += 1    
print(count)
除此之外,您还可以使用使其更加简洁:

count = sum(a == user_character for a in user_string)

如果a==用户\字符:?循环一次遍历整个输入字符串一个字符,该字符被放入变量a中…谢谢。但我没有注意到: