【基础入门题】2021.11.29
给定一行字符串,分别统计出其中英文字母、数字、空格和其它字符的个数。
编程语言:包括但不限于Python
题目来源:派森特给站每日刷题频道
————————————————
方法一:
def Character(Str): letters,digits,spaces,others = 0,0,0,0 for s in Str: if 'a'<=s<='z' or 'A'<=s<='Z': letters += 1 elif '0'<=s<='9': digits += 1 elif s==' ': spaces += 1 else: others += 1 return letters,digits,spaces,others print(Character('I am Hann Yang, my email is [hann@126.com].'))
方法二:与string库中的几个常量比较
def Character(Str): import string letters,digits,spaces,others = 0,0,0,0 for s in Str: if s in string.ascii_letters: letters += 1 elif s in string.digits: digits += 1 elif s in string.whitespace: #whitespaqce除了空格还包括'\t\n\r\x0b\x0c' spaces += 1 else: others += 1 return letters,digits,spaces,others print(Character('I am Hann Yang, my email is [hann@126.com].'))