题解 | #HJ40 统计字符#
统计字符
https://www.nowcoder.com/practice/539054b4c33b4776bc350155f7abd8f5
方法1-常规
s = input() # 初始化计数器 alpha, space, digit, other = 0, 0, 0, 0 # 遍历字符串,统计各类字符的个数 for char in s: if char.isalpha(): alpha += 1 elif char.isspace(): space += 1 elif char.isdigit(): digit += 1 else: other += 1 print(alpha) print(space) print(digit) print(other)
方法2-正则表达式
import re s = input() print(len(re.findall(r'[a-zA-Z]', s))) print(len(re.findall(r'\s', s))) print(len(re.findall(r'\d', s))) print(len(re.findall(r'[^a-zA-Z0-9\s]', s)))