如何只计算字符串中的字母

你好,
我遇到了一种计算输入字符串中字母字符数量的方法,以及一种计算数字字符数量的方法。我一直在尝试ispha和isdigit字符串方法,但什么也想不出来。到目前为止,我有:

选择 | 换行 | 行号
  1. def main():
  2.     sentence = input('Enter a sentence: ')
  3.     Stats(sentence)
  4.  
  5. def Stats(input):
  6.     print('Total characters:', character(input))
  7.     print('Letters:', letter(input))
  8.     print('Digits:', digit(input))
  9.  
  10. def character(input):
  11.     count = 0
  12.     for char in input:
  13.         count += 1
  14.     return (count)
  15.  
  16. def letter(input):
  17. # This is where I'm stuck.  Not sure how to use isalpha() 
  18. # to make this work
  19.  
  20. def digit(input):
  21. # here as well, but with the isdigit().
# 回答1


嗨。如果使用代码标签(#BUTTON),它会更容易一些。
不过,您的代码结构是否非常好和清晰。
下面是如何将字符改写成字母

选择 | 换行 | 行号
  1. def letter(input)
  2.     count=0
  3.     for char in input:
  4.         if isalpha(char):
  5.             count += 1
  6.     return count

祝好运!
在西方,我不认为IsAlpha是在Plane Python中定义的,所以可能是您单独定义了它,或者是导入了什么?如果不是,ispha函数可能如下所示:

选择 | 换行 | 行号
  1. def isalpha(x):
  2.     return x in "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
# 回答2


IsAlpha()和isDigit()是字符串方法,返回布尔值。

选择 | 换行 | 行号
  1. >>> "a".isalpha()
  2. True
  3. >>> "1".isdigit()
  4. True
  5. >>> "1".isalpha()
  6. False
  7. >>> 
# 回答3


啊,是。LOL。我告诉过你我做的蟒蛇还不够多

标签: python

添加新评论