Python
基础语法
输出
输出到终端
print(50)
print("hello world")
print(5+4)
输出到文件
fp = open('D:/text.txt','a+')
print("hello world", file = fp)
fp.close()
# 注意点:路径要写对,a+的意思是以读写方式打开,如果没有这个文件就创建一个
# 再次执行程序则会追加内容
数据类型与类型转换
数据类型
常用数据类型:int, float, bool, str
bool 类型:true/false,非零值为真,0 为假,空列表/空元组等为假
name = "hello"
print(id(name), type(name), name)
# id 函数用于获取地址, type 函数用于获取变量类型
# 为空的对象布尔值为 0(如空列表,空值, 空字典等)
print(bool([]))
print(bool(None))
print(bool(()))
print(bool({}))
数据类型转换
# 函数:int,float,bool,str 等
print("hello"+"world")
# 加号表示两个字符串连接
print("hello"+str(2353113))
# str 函数将 int 类型转换为 str 类型
print(bool(3131))
# float 类型转换 int 类型为截断小数部分
print(int("123"))
# str 类型转化 int 类型必须为整数字符串(带小数不能转)
print(float("123.123"))
# str 类型转换 float 类型需要是小数字符串
强制类型转化来求输入数的和
x = int(input("please input a integer:"))
print(type(x), x)
# input 函数的返回值为 str 类型
y = int(input("please input a integer:"))
print(x+y)
注释
# 这是一个注释
'''
注释1
注释2
'''
顺序结构
分支选择结构
score = int(input("please input a integer:"))
if score==100:
print("best!")
elif score <100 and score> = 80:
print("good!")
elif score <80 and score> = 60:
print("normal!")
else:
print("bad!")
# 用 or and 逻辑运算符,elif 相当于 else if
num = int(input("please input a integer:"))
if num==50:
pass
else:
print("hello world")
# pass 为空语句,仅作占位作用
条件运算符
num_a = int(input("please input a integer:"))
num_b = int(input("please input another integer:"))
max = num_a if num_a > num_b else num_b
print("最大值为:", max)
# 格式:x if 条件 else y
# 当条件为真时返回 x,为假时返回 y
循环和列表
range函数
arr = range(1,10,2)
# range 函数用法:第一个参数为起始值(默认为 0),第二个参数为结束值(不包括端点值),第三个参数为步长(方差)
# 作用:用于生成一个序列
print(list(arr))
print(10 in arr)
print(10 not in arr)
# 用 in 和 not in 可以判断一个数是否在一个序列中
循环
# 循环分类:while 循环/for in 循环
sum_ji = 0
sum_ou = 0
number = 1
while number <= 100:#计算 1 到 100 的偶数奇数分别的累加和
if number%2==0:
sum_ou+= number
else:
sum_ji+= number
number+= 1
print("偶数为:", sum_ou, "奇数为:", sum_ji)
for item in "python":
print(item)
# 含义为:从 python 这个序列中依次取出一个元素来赋给 item
for i in range(1,10,2):
print(i)
for i in range(5):
print("life is precious")
# range 函数可用于控制循环次数
for i in range(100,1000):#输出 100 到 1000 间的所有的水仙花数
b = int(i/100)
s = int(i/10%10)
g = int(i%10)
if b **3+s** 3+g**3==i:
print(i, "\t")
break和continue
# break 和 continue 可以控制循环的进行
for i in range(3):#打印三行四列的矩形
for j in range(4):
print("*", end ="\t ")
print("\n")
for i in range(1,10):
for j in range(1, i+1):
print(i*j, end = "\t")
print("\n")
字典
字典特点
创建
# 字典:用花括号定义,以键值对的方式存储数据(无序)
# 字典的创建方式:
# 花括号直接创建和 dict 函数创建
dict1 ={"yyf": 123, "hxj": 45,45: 78}
print(dict1)
dict2 = dict(name = "yyf", age = 12)
print(dict2)
# 前面的是键名,后面的是键值
元素获取
# 键名索引获取和 get 函数获取
print(dict1 ["yyf"])
print(dict1.get("yyf"))
print(10 in dict1)
print(10 not in dict1)
新增和修改元素
# 字典的新增和修改
dict1 ["王五"] = 456
print(dict1)
dict1 ["王五"] = 123
print(dict1)
删除和清空
# del 函数和 clear 函数
del dict1 ["yyf"]
print(dict1)
dict1.clear()
print(dict1)
字典视图
# 函数:keys,values,items
dict1 ={"yyf": 123, "hxj": 45,45: 78}
keys = dict1.keys()
print(keys, type(keys))
print(list(keys))#将字典中的键名转化为列表
# keys 函数用法:用于获取字典中所有的键名
values = dict1.values()
print(values, type(values))
print(list(values))#将所有的键值化为列表
# values 函数用于获取所有键值
items = dict1.items()
print(items, type(items))
print(list(items))#转化成一元组为元素的列表
# items 函数用于获取所有的键值对
遍历
# 字典的遍历
for item in dict1:
print(item, dict1 [item], dict1.get(item))
# 只会取出键名,要遍历键值需要用后面两个的形式
字典生成式
# 字典生成式
keyname = ["yyf", "hxj", "my"]#用列表存储键名
keyvalue = [12,15,16]#列表存储键值
dict3 ={keyname: keyvalue for keyname, keyvalue in zip(keyname, keyvalue)}
#zip 函数用于打包数据
print(dict3)
#若键名和键值个数不匹配, 则以少的为基准
元组
创建
# 元组的创建方式
# 直接小括号创建和 tuple 函数
t =("hello world",12,15,6)
print(t, type(t), id(t))
t1 = tuple(("hello", "tom",12,15))
print(t1, type(t1), id(t1))
# 注:当元组只有一个元素时要加上逗号,否则会认为它是 str 类型
t2 =("hello")#str 类型
print(type(t2))
t2 =("hello",)
print(type(t2))#元组类型
获取元素
# 元组元素的获取
t3 =("python", [1,3], "tom")
print(t3 [0], type(t3 [0]), id(t3 [0]))
print(t3 [1], type(t3 [1]), id(t3 [1]))
print(t3 [2], type(t3 [2]), id(t3 [2]))
# t3 [0] = 100 (修改元组的元素会报错)
# 但是修改元组中的元素的元素是可以的(如修改其中的列表)
t3[1][0] = 3
print(t3[1])
遍历
# 元组的遍历
for item in t3:
print(item)
集合
创建
# 集合的创建
# 花括号创建和 set 函数创建
s ={1,1,2,2,5,6,8,9}
print(s, type(s), id(s))
# 注:集合的元素不能重复
s1 = set([1,2,3,4,5,6,6,6,6])
print(s1, type(s1), id(s1))
# set 函数可以将列表转化为集合,同时去掉重复值
s1 = set((1,2,3,4,4,4,65))
print(s1, type(s1), id(s1))
# set 函数也可将元组转化为集合
# 空集合创建不能直接使用空花括号,要有 set 函数创建
s3 = set()
print(s3, type(s3), id(s3))
元素增删改查
# 集合的增删改查操作
s4 ={1,2,3,6,4,5,8,9, "hello"}
# 判断操作
print(10 in s4)
print(10 not in s4)
# 增加操作
s4.add(80)#add 函数一次添加一个元素
print(s4)
s4.update({10,50,60,30})#update 函数一次可添加多个元素
print(s4)
s4.update(("world",45,78))
print(s4)
# 删除操作
s4.remove(50)#remove 函数一次删除一个元素
print(s4)
s4.discard(60)
print(s4)#discard 函数一次删除一个元素
s4.pop()#pop 函数一次删除任意一个元素(pop 函数不能加参数)
print(s4)
s4.clear()#clear 函数用于清空集合
print(s4)
集合之间的操作
# 集合间的关系
# 两个集合是否相等
s1 ={1,2,3}
s2 ={3,2,1}
print(s1==s2)
#判断标准:集合元素相等就相等(原因:集合为无序)
# 子集超集等用对应函数可判断
# 集合的数学操作
# 交集操作
s1 ={10,20,30,40,50}
s2 ={20,30,50,60}
print(s1 & s2)
# &为取交集操作
# 并集操作
print(s1 | s2)
# |为取并集操作
# 差集操作(即两个集合去掉相同的部分)
print(s1 - s2)
print(s2 - s1)
# -为取差集操作
集合生成式
# 集合生成式
s ={i*i for i in range(1,10)}
# 把列表的 [] 改为{}就是集合生成式
print(s)
函数
创建格式:
def 函数名(参数):
函数体
return xxx(可没有返回值)
example:
def fun(x, y):
print(x+y)
# 与 c 一样,函数的形参只是副本,不能直接改变实参的值
a = 10
b = 20
print(a, b)
def fun_1(x, y):
x = 100
y = 200
fun_1(a, b)#并不改变 a 和 b 的值
print(a, b)
def fun_2(num):
odd = []#存奇数
even = []#存偶数
for i in num:
if i%2:
odd.append(i)
else:
even.append(i)
return odd, even
lst = [10,29,34,23,44,53,55]
print(fun_2(lst))
#有多个返回值时,得到的是元组,如果返回值为一个,则返回原类型
def fun_3():
return "hello", "world"
print(fun_3())
可变参数
# 函数参数定义
def fun_4(*att):#可变的位置参数(元组类型)
print(att)
fun_4(10)
fun_4(10,20)
fun_4(10,20,500)
# 注:可变的位置参数只能定义一个
面向过程和对象
面向过程
面向过程是一种以事件为中心的编程思想,编程的时候把解决问题的步骤分析出来,然后用函数把这些步骤实现,在一步一步的具体步骤中再按顺序调用函数。
举个例子,下五子棋,面向过程的设计思路是首先分析解决这个问题的步骤:
- 开始游戏
- 黑子先走
- 绘制画面
- 判断输赢
- 轮到白子
- 绘制画面
- 判断输赢
- 返回步骤
- 输出最后结果
面向对象
在日常生活或编程中,简单的问题可以用面向过程的思路来解决,直接有效,但是当问题的规模变得更大时,用面向过程的思想是远远不够的。
所以慢慢就出现了面向对象的编程思想。世界上有很多人和事物,每一个都可以看做一个对象,而每个对象都有自己的属性和行为,对象与对象之间通过方法来交互。
面向对象是一种以“对象”为中心的编程思想,把要解决的问题分解成各个对象,建立对象的目的不是为了完成一个步骤,而是为了描叙某个对象在整个解决问题的步骤中的属性和行为。
在下五子棋的例子中,用面向对象的方法来解决的话,首先将整个五子棋游戏分为三个对象:
- 黑白双方,这两方的行为是一样的。
- 棋盘系统,负责绘制画面
- 规则系统,负责判定犯规、输赢等。
注:python 中一切皆对象
example:
# 类和对象
class Student:
pass
# 注:定义类的规范:类名可以由一个/多个单词组成,但每个单词的首字母需要大写(规范)
# 注:由 class 关键字来定义
print(Student,'\n', type(Student),'\n', id(Student))
# 此处的 Stduent 为类对象
class Mytest:
def __init__(self, name, age): # 成员函数,声明需要与外部交互的参数(类的属性)
self.name = name
self.age = age
native_pace = "吉林"#类属性
def eat(self):#示例方法
print("学生在吃饭")
@staticmethod
#用 staticmethod 来修饰的是静态方法,不能用 self
def method():
print("我使用 staticmethod 来修饰")
@classmethod
#用 classmethon 修饰的是类方法,参数为 cls(class)
def cm(cls):
print("我使用 classmethod 来修饰")
# 注:定义在类里的变量称为类属性
# 类属性的使用方式:
# 类名访问
print(Mytest.native_pace)
#静态方法的使用方式:(类名访问)
Mytest.method()
#类方法的使用方式:(类名访问)
Mytest.cm()
# 动态绑定属性和方法
#创建实例对象
mytt1 = Mytest("yyf",16)
mytt2 = Mytest("hxj",46)
print(id(mytt1), id(mytt2))
#为 mytt1 动态绑定属性
mytt1.gender = "n"
print(mytt1.name, mytt1.age, mytt1.gender)
print(mytt2.name, mytt2.age)
# 分别调用方法
# 要用实例对象来调用实例方法
mytt1.eat()
mytt2.eat()
# 动态绑定方法
def fun():
print("hello world")
#为 mytt2 动态绑定方法(外部定义的函数)
mytt2.fun = fun
mytt2.fun()
#为类动态绑定属性
Mytest.gender = "n"
print(mytt2.gender)
字符串常用操作
字符串为不可变的序列
字符串的驻留机制
a = "python"
b ='python'
c ='''python'''
print(a, id(a))
print(b, id(b))
print(c, id(c))
# 类似 c,字符串实际相当于地址,故 a,b,c 的地址都指向了字符串的地址
# 对相同的字符串只保留一份拷贝,后续创建相同字符串时,不会创建新的内存空间,而是把该地址赋给新的变量
字符串查找
# 函数:index/rindex,find/rfind
str = "hello, hello"
print(str.index("lo"))
print(str.rindex("lo"))
print(str.find("lo"))
print(str.rfind("lo"))
#index/find 表示正向查找,rindex/rfind 表示逆向查找
# 建议主要使用 find/rfind 函数进行查找
大小写转换
# 字符串大小写转换的方法
# 函数:upper,lower, swapcase, title
s = "hello, python"
s1 = s.upper()
print(id(s), s, id(s1), s1)
# 注:转换大小写会新创建一个对象
s2 = s1.lower()
print(s2)
s3 = "Hello, Python"
s4 = s3.swapcase()
print(s4)
s3 = "hello, python"
s5 = s3.title()
print(s5)
# 函数用法:upper/lower 用于将大写/小写转化为小写/大写,swapcase 用于将大小写互换,
# title 用于将每个单词的首字符大写,其余小写
字符串对齐
# 将字符串对齐的操作
# 函数:center(居中对齐),ljust(左对齐),rjust(右对齐),zfill(右对齐)
s6 = "hello, python"
print(s6.center(30,"*"))
# center 函数用法:第一个参数为指定宽度,第二个参数为多余位置的填充符
print(s6.ljust(30,"*"))
# ljust 函数用法:同上
print(s6.rjust(30,"*"))
# rjust 函数用法:同上
print(s6.zfill(30))
# zfill 函数用法:只有一个指定宽度的参数,其余空位用 0 补齐
字符串分割
# 字符串劈分(分割)操作:
# 函数:split 和 rsplit
# 注:分割后为列表
str1 = "hello python and world"
lst = str1.split(sep = " ")
print(lst)
str2 = "hello|world|and|python"
lst1 = str2.split(sep = "|")
print(lst1)
lst2 = str2.split(sep = "|", maxsplit = 2)
print(lst2)
# split 函数用法:sep 指定分割符,maxsplit 指定最大分割次数
# split 和 rsplit 函数的区别:rsplit 为从右侧开始劈分
字符串替换和合并
# 字符串的替换和合并
# 函数:replace 和 join
str3 = "hello world and python python python"
str3_1 = str3.replace("python", "java",2)
print(str3, "\n", str3_1)
# replace 函数用法:第一个参数表示待替换的字符串,第二个参数表示替换的内容,第三个参数表示替换几次
str4 = ["hello", "world", "python"]
str4_1 ='|'.join(str4)
print(str4_1)
str5 =("hello", "world", "python")
str5_1 ='|'.join(str5)
print(str5_1)
str6 = "hello"
str6_1 ='*'.join(str6)
print(str6_1)
# join 函数用法:参数为列表或元组,当参数为字符串时,会当成序列来进行合并(前面跟上连接的符号)
# 作用: 将其转化为字符串
字符串比较
# 字符串比较操作:
# 函数:ord、chr
# 关于 ord 和 chr 函数的说明:ord 用于得到字符的原始值,chr 用于将原始值转化为字符
# 字符串比较的都是原始值,且为一个一个比较,一旦得出结果,后续不再比较
ord_= ord("杨")
print("原始值为:", ord_)
print("转化为字符为:", chr(ord_))
print("apple" > "app")
# 字符串比较符和运算符相同
# 注:is 和==的区别:is 比较的是地址,==比较的是值是否相同
字符串切片
# 字符串的切片操作:
# 字符串可看为一个不可变的列表
str7 = "hello world python"
str8 = str7 [: 5]
print(str8)
字符串格式化
# 字符串的格式化
name = "yyf"
age = 15
print("name =%s, age =%d" % (name, age))
# 占位符与 c 的相同
# 精度与宽度操作与 c 的相同
print("%0.3f"%3.1415926)
print("%5d"%10)
字符串编码与解码
# 字符串的编码和解码
# 函数:encode、decode
# 编码
s = "明月几时有"
print(s.encode(encoding = "GBK"))# 采用 GBK 编码方式
print(s.encode(encoding = "UTF-8"))# 采用 UTF-8 编码方式
# 解码
byte1 = s.encode(encoding = "GBK")
byte2 = s.encode(encoding = "UTF-8")
print(byte1.decode(encoding = "GBK"))
print(byte2.decode(encoding = "UTF-8"))
# 注:解码方式要和编码方式一致
文件操作
文件编码格式介绍:UTF-8, GBK 等
python 默认文件编码为 UTF-8 编码
文件的读写
文件的读写(IO 操作)
open() 函数用于创建或打开指定文件,该函数的常用语法格式如下:
file = open(file_name [, mode ='r' [ , buffering =-1 [ , encoding = None ]]])
此格式中,用 [] 括起来的部分为可选参数,即可以使用也可以省略。其中,各个参数所代表的含义如下:
需要注意的是,如果要打开的文件和当前执行的代码文件位于同一目录,则直接写文件名即可;否则,此参数需要指定打开文件所在的完整路径。
以 Windows 为例,其默认为 cp936(实际上就是 GBK 编码)。
file = open("d:/text.txt",'r')
print(file.readlines())
file.close()
# 注:每次进行文件操作时都要执行关闭操作
# 或者使用with 上下文管理(自动关闭文件句柄)
with open("d:/text.txt",'r') as f:
print(f.readlines())
# 常用的文件打开模式
# r, w, b, wb, rb 等
# 文件对象的常用方法:
# read、readline、readlines 等
练习
# 1.编写一个可以计算给定数的阶乘的程序。结果应该以逗号分隔的顺序打印在一行上。
# 法一:循环
number = int(input("please input a integer:"))
pro = 1
for i in range(1, number+1):
pro*= i
print(pro)
# 法二:递归
def jiecheng(number):
if number==1 or number==0:
return 1
else:
return number*jiecheng(number-1)
number = int(input("please input a integer:"))
print(jiecheng(number))
# 2.使用给定的整数 n,编写一个程序生成一个包含(i, i*i)的字典,该字典包含 1 到 n 之间的整数(两者都包含)。
# 然后程序应该打印字典。
# 假设向程序提供以下输入: 8
# 则输出为:{1: 1,2: 4,3: 9,4: 16,5: 25,6: 36,,7: 49,8: 64}
# 法一:字典生成式
number = int(input("please input a integer:"))
dic ={i: i*i for i in range(1, number+1)}
print(dic)
# 法二: 赋值
number = int(input("please input a integer:"))
dic = dict()
for i in range(1, number+1):
dic [i] = i*i
print(dic)
# 3.编写一个程序,接受逗号分隔的单词序列作为输入,按字母顺序排序后按逗号分隔的序列打印单词。
# 假设向程序提供以下输入:
# without, hello, bag, world
# 则输出为:
# bag, hello, without, world
string = input("please input some words:")
lit = [x for x in string.split(',')]
lit.sort()
print(','.join(lit))
# 4.编写一个程序,接受一行序列作为输入,并在将句子中的所有字符大写后打印行。
# 假设向程序提供以下输入:
# Hello world
# Practice makes perfect
# 则输出为:
# HELLO WORLD
# PRACTICE MAKES PERFECT
lines = []
while 1:
s = input("please input a string:")
if s:
lines.append(s.upper())
else:
break
for i in lines:
print(i)
# 5.编写一个程序,接受一系列空格分隔的单词作为输入,并在删除所有重复的单词并按字母数字排序后打印这些单词。
# 假设向程序提供以下输入:
# hello world and practice makes perfect and hello world again
# 则输出为:
# again and hello makes perfect practice world
string = input("please input a string:")
lit = [x for x in string.split(" ")]
print(' '.join(sorted(list(set(lit)))))#先通过元组的特性去重,再转化为列表处理
# 6.编写一个程序,接受一系列逗号分隔的 4 位二进制数作为输入,然后检查它们是否可被 5 整除。
# 可被 5 整除的数字将以逗号分隔的顺序打印。
# 例:
# 0100,0011,1010,1001
# 那么输出应该是:
# 1010
string = input("请输入一串以逗号分隔的二进制数:")
lit = [x for x in string.split(',')]
result = []
for i in lit:
int_d = int(i,2)#int 函数用于将数转化为十进制,第二个参数用于指定进制
#print(int_d)
if int_d%5==0:
result.append(i)
print(','.join(result))
# 7.编写一个接受句子的程序,并计算大写字母和小写字母的数量。
# 假设为程序提供了以下输入:
# Hello world!
# 然后,输出应该是:
# 大写实例 1
# 小写实例 9
dic ={"upper": 0, "lower": 0}
string = input("please input a string:")
for i in string:
if i.isupper():#isupper() 方法检测字符串中所有的字母是否都为大写。
dic ["upper"]+= 1
elif i.islower():#islower() 方法检测字符串中所有的字母是否都为小写。
dic ["lower"]+= 1
else:
pass
print("大写字母有:%d, 小写字母有:%d" % (dic ["upper"], dic ["lower"]))
# 8.使用列表推导来对列表中的每个奇数。 该列表由一系列逗号分隔的数字输入。
# 假设为程序提供了以下输入:
# 1,2,3,4,5,6,7,8,9
# 然后,输出应该是:
# 1,3,5,7,9
string = input("please input a string:")
lit = [x for x in string.split(',') if int(x)%2!= 0]#推导式后可跟 if 表达式
print(','.join(lit))
# 9.网站要求用户输入用户名和密码进行注册。编写程序以检查用户输入的密码的有效性。
# 以下是检查密码的标准:
# 1. [a-z] 之间至少有 1 个字母
# 2. [0-9] 之间至少有 1 个数字
# 1. [A-Z] 之间至少有一个字母
# 3. [$#@]中至少有 1 个字符
# 4.最短交易密码长度:6
# 5.交易密码的最大长度:12
# 您的程序应接受一系列逗号分隔的密码,并将根据上述标准进行检查。将打印符合条件的密码,每个密码用逗号分隔。
# 例:如果以下密码作为程序的输入:
# ABd1234@1, a F1#,2w3E*,2We3345
# 然后,程序的输出应该是: ABd1234 @ 1
import re
string = input("please input the password:")
result = []
lit = [x for x in string.split(',')]
for i in lit:
if len(i)<=12 and len(i)> = 6:
if re.search('[a-z]', i) and re.search('[0-9]', i) and re.search('[A-Z]', i) and re.search('[$#@]', i):
pass
else:
continue
result.append(i)
else:
continue
print(','.join(result))
# 10.有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少?
for i in range(1,5):
for j in range(1,5):
for k in range(1,5):
if i!= j and i!= k and j!= k:
print(i *100+j* 10+k, end ='\t')
# 11.输入某年某月某日,判断这一天是这一年的第几天?
year = int(input('year:\n'))
month = int(input('month:\n'))
day = int(input('day:\n'))
months = (0,31,59,90,120,151,181,212,243,273,304,334)
if 0 < month <= 12:
sum = months [month - 1]
else:
print ('data error')
sum += day
leap = 0
if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
leap = 1
if (leap == 1) and (month > 2):
sum += 1
print ('it is the %dth day.' % sum)
# 12.输入三个整数 x, y, z,请把这三个数由小到大输出。
lit = []
for i in range(3):
number = int(input("please input a integer:"))
lit.append(number)
lit.sort()
for item in lit:
print(item, end ='\t')
# 13.斐波那契数列(Fibonacci sequence),又称黄金分割数列,指的是这样一个数列:
# 0、1、1、2、3、5、8、13、21、34、……。
# 在数学上,费波那契数列是以递归的方法来定义:
def feibonacci(n):
if n <=2 and n> 0:
return 1
else:
return feibonacci(n-1)+feibonacci(n-2)
count = int(input("please input the count you want:"))
for i in range(1, count+1):
print(feibonacci(i), end ='\t')
# 14.判断 100-1000 之间有多少个素数,并输出所有素数。
count = 0
for i in range(100,1001):
for j in range(2, i+1):
if i%j==0:
break
if j >= i:
print(i, end ='\t')
count+= 1
print("共有%d 个" % count)
# 15.输入一行字符,分别统计出其中英文字母、空格、数字和其它字符的个数。
dic ={'ying': 0,'kong': 0,'num': 0,'oth': 0}
while 1:
string = input("please input a string:")
if not string:
break
for i in string:
if i.isalpha():
dic ['ying']+= 1
elif i.isspace():#isspace 函数用于判断是否空格
dic ['kong']+= 1
elif i.isdigit():
dic ['num']+= 1
else:
dic ['oth']+= 1
print("英文字母:%d, 空格:%d, 数字:%d, 其他字符:%d" % (dic ['ying'], dic ['kong'], dic ['num'], dic ['oth']))
作者:d1k3siy