[英]adding the amount of letters there are in a string in python
我的代码将字母加在一起。 但我只需要计算字母的数量。
例如,对于输入字符串“a12a”,output 将为2
,因为有 2 个字母。
def countingletters(st):
empty = []
for i in st:
if i.isalpha():
empty += str(i)
return empty
尝试
def countingletters(st):
empty = []
for i in st:
if i.isalpha():
empty+= str(i)
count_letters = len(empty)
print(count_letters)
return empty
只需用字母计算数组的 len 即可。 我不知道您是否要打印结果,但这就是答案。
它将字母加在一起
不完全......它将字母单独附加到列表中,而不是将所有字母组合在一起
您可以简单地return len(empty)
,但是维护一个列表而不仅仅是一个 integer 并不是最佳解决方案
方法 1:使用列表(如您所做的那样)
def countingletters(st):
empty = []
for i in st:
if i.isalpha():
empty += str(i)
return len(empty)
# test
print(countingletters("a12a")) # display 2
方法2:使用计数器
def countingletters(st):
cpt = 0 # the counter
for i in st:
if i.isalpha():
cpt += 1
return cpt
# test
print(countingletters("a12a")) # display 2
方法 3:使用列表推导
def countingletters(st):
return len([i for i in st if i.isalpha()])
# test
print(countingletters("a12a")) # display 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.