题目:
输入一行字符,分别统计出其中英文字母、数字、空格和其他字符的个数。
输入格式:
一行字符,长度不超过200
输出格式:
统计值
样例输入:
aklsjflj123 sadf918u324 asdf91u32oasdf/.';123
样例输出:
23 16 2 4
代码示例:
def count_strings(s):
chars = 0
digits = 0
spaces = 0
others = 0
for char in s:
if char.isalpha():
chars += 1
elif char.isdigit():
digits += 1
elif char.isspace():
spaces += 1
else :
others += 1
return chars,digits,spaces,others
s = input()
strings = count_strings(s)
for i in strings:
print(i,end =' ')
收获:
字符串中数字 , 字母, 空格,其他符号的分离:
法一
char.isalpha(): # 判断字符是否为字母
char.isdigit(): # 判断字符是否为数字
char.isspace(): # 判断字符是否为空格
法二:
import re
datas_in_re = input()
# 以列表的形式返回匹配的全部子串
cha = re.findall(r'[a-zA-Z]', datas_in_re)
# r的意思是使用原生字符,防止转义
# [a-zA-Z]表示26个英文字母,包括大小写
num = re.findall(r'[0-9]', datas_in_re)
# [0-9]表示0到9十个数字
blk = re.findall(r'[ ]', datas_in_re)