list =["jojo","gardan","giga"]
number_of_a = 0
for item in list:
if "a" in item:
number_of_a += 1
print("there is "+str(number_of_a)+ " a's in "+ item)
else :
print("sorry")
list_ =["jojo","gardan","giga"]
for item in list_:
number_of_a = 0
for i in item:
if i == 'a':
number_of_a += 1
else:
continue
if number_of_a:
print("there is "+str(number_of_a)+ " a's in "+ item)
else :
print("sorry")
l = ["jojo", "gardan", "giga"]
number_of_a = 0
for item in l:
if "a" in item:
number_of_a += 1
print("there is " + str(number_of_a) + " a's in " + item)
else:
print("sorry")
您只是检查每个字符串中是否存在}将返回
a
,而不是检查其中有多少个字符串^如果字符串中有字母“a”,则{True
,否则返回False。然后在计数器上加1因此,这里第一个字符串将返回False,变量将保持为0,但第二个字符串将其更改为1,最后一个字符串将其更改为2。如果要计算每个字符串中“a”的数量,需要确保为每个字符串重新设置计数器的值,然后需要实际计算“a”的数量,例如迭代所有字符或使用其他人建议的
count
:我假设您想知道列表中每个元素中有多少个“a”。这是代码
输出: 很抱歉 加尔丹有1个a giga中有2个a
所以根据我的理解,你想要计算字符串中字母的出现次数
在python中,最简单的方法是使用count方法,如下所示:
相关问题 更多 >
编程相关推荐