我正在编写一个代码,以使用循环计算给定输入内的空格/数字/字母的数量。我正在尝试使用.isdigit()和.isalpha()方法来查看字符串中的每个字母是否为字母或数字,如果为true,则将其添加到计数中。我的代码对我来说看起来很完美,但是当我运行它时,我只会得到长度和空格的计数(这不是使用.isspace()方法)。也许在更新循环中的计数时我搞砸了,但是再次。这一切对我来说都很不错,有人可以帮助我朝正确的方向发展吗?
def main():
sentence = input('Enter a sentence: ')
printStats(sentence)
def printStats(input):
print('Statistics on your sentence: ')
print(' Characters:', charCount(input))
print(' Letters:', letterCount(input))
print(' Digits:', digitCount(input))
print(' Spaces:', spaceCount(input))
def charCount(input):
for char in input:
return len(input)
#Section below is where I need help
def letterCount(input):
count=0
for letter in input:
if input.isalpha():
count += 1
return count
def digitCount(input):
count=0
for digit in input:
if input.isdigit():
count += 1
return count
#Section above is where I need help
def spaceCount(input):
for space in input:
return input.count(" ")
main()
谢谢你的时间
您需要执行letter.isalpha()和digit.isdigit(),而不是在整个输入上调用它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句