题解 | #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)))

全部评论

相关推荐

03-15 12:48
门头沟学院 Java
牛牛要早起:这个一般就跟你说有高薪,然后叫你买车,之后血亏
点赞 评论 收藏
分享
爱喝雪碧:我也投了这家,他最后两行我不懂,问什么意思,不回复我了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务