🌴 2022.5.25 下午 实验
实验三 函数
前言
🎬本文章是 【Python语言基础】 专栏的文章,主要是上课的随堂笔记与练习
🔗Python专栏 传送门
📽实验源码已在Github整理
题目一
编写一个函数func(str),计算并返回字符串str中的数字、字母及其他类型字符的个数
问题分析
在func函数中利用元组定义数字、字母、空格、其它,并初始化为0。之后利用for循环对字符遍历,依次if判断是哪种字符类型
内置函数:
isdigit ()
判断数字isalpha ()
判断字母isspace ()
判断空格
代码
"""
@Author:张时贰
@Date:2022年05月28日
@CSDN:张时贰
@Blog:zhangshier.vip
"""
content = input ( '输入字符串' )
def func(s):
num = 0
alpha = 0
space = 0
others = 0
dic = {
'num': 0,
'alpha': 0,
'space': 0,
'other': 0
}
for i in s:
if i.isdigit ():
dic[ 'num' ] += 1
elif i.isalpha ():
dic[ 'alpha' ] += 1
elif i.isspace ():
dic[ 'space' ] += 1
else:
dic[ 'other' ]