1. 列表
1)append() 增加列表项
#!/usr/bin/python3
list1=["google" ,"zhihu" ,"newbie" ]
print ("更新前列表:" ,list1)
list1.append("baidu" )
print ("更新后列表:" ,list1)
>>输出:
更新前列表: ['google' , 'zhihu' , 'newbie' ]
更新后列表: ['google' , 'zhihu' , 'newbie' , 'baidu' ]
2)del 删除列表项
#!/usr/bin/python3
list1=["google" ,"zhihu" ,"newbie" ]
print ("删除前列表:" ,list1)
del list1[2]
print ("删除后列表:" ,list1)
>>输出:
删除前列表: ['google' , 'zhihu' , 'newbie' ]
删除后列表: ['google' , 'zhihu' ]
3)列表操作符
Python 表达式
结果
描述
len([1, 2, 3])
3
长度
[1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
组合
['Hi!'] * 4
['Hi!', 'Hi!', 'Hi!', 'Hi!']
重复
3 in [1, 2, 3]
True
元素是否存在于列表中
for x in [1, 2, 3]: print(x, end=" ")
1 2 3
迭代
4)列表拼接
#!/usr/bin/python3
list1=["google" ,"zhihu" ,"newbie" ]
print ("拼接前列表:" ,list1)
list1+=[1,2,3,4,5]
print ("拼接后列表:" ,list1)
>>输出:
拼接前列表: ['google' , 'zhihu' , 'newbie' ]
拼接后列表: ['google' , 'zhihu' , 'newbie' , 1, 2, 3, 4, 5]
5)列表嵌套
#!/usr/bin/python3
list1=['a' ,'b' ,'c' ]
list2=[1,2,3]
x=[list1,list2]
print ("嵌套列表:" ,x)
print (x[0])
print (x[1])
>>输出:
嵌套列表: [['a' , 'b' , 'c' ], [1, 2, 3]]
['a' , 'b' , 'c' ]
[1, 2, 3]
6)列表比较(operator模块)
operator.lt(a, b)
operator.le(a, b)
operator.eq(a, b)
operator.ne(a, b)
operator.ge(a, b)
operator.gt(a, b)
operator.__lt__(a, b)
operator.__le__(a, b)
operator.__eq__(a, b)
operator.__ne__(a, b)
operator.__ge__(a, b)
operator.__gt__(a, b)
operator.lt(a, b) 与 a < b 相同, operator.le(a, b) 与 a <= b 相同,operator.eq(a, b) 与 a == b 相同,operator.ne(a, b) 与 a != b 相同,operator.gt(a, b) 与 a > b 相同,operator.ge(a, b) 与 a >= b 相同。
#!/usr/bin/python3
import operator
a=[1,2]
b=[2,3]
c=[2,3]
print (operator.eq(a,b))
print (operator.__eq__(a,b))
print (operator.eq(b,c))
print (operator.__eq__(b,c))
print (operator.lt(a,b))
>>输出:
False
False
True
True
True
7)列表的函数
序号
函数
1
len(list)列表元素个数
2
max(list)返回列表元素最大值
3
min(list) 返回列表元素最小值
4
list(seq)将元组转换为列表
Python包含以下方法:
序号
方法
1
list.append(obj)在列表末尾添加新的对象
2
list.count(obj)统计某个元素在列表中出现的次数
3
list.extend(seq) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4
list.index(obj)从列表中找出某个值第一个匹配项的索引位置
5
list.insert(index, obj)将对象插入列表中指定的索引位置
6
list.pop([index=-1])移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7
list.remove(obj)移除列表中某个值的第一个匹配项
8
list.reverse()反向列表中元素,对列表中的值反向排序
9
list.sort( key=None, reverse=False)对原列表进行永久排序
10
sorted(list,reverse=False)对列表临时排序
11
list.clear()清空列表
12
list.copy()复制列表
#!/usr/bin/python3
list1=[1,2,3,4]
list2=["a" ,"b" ,"c" ]
list1.append(4)
print (list1)
list1.extend(list2)
print (list1)
list1.insert(0,"jiaxing" )
print (list1)
print (list1.count(4))
print (list1.index(4))
print (list1.pop(0))
list1.remove(4)
print (list1)
list1.reverse()
print (list1)
list2.sort()
print (list2)
list2.sort(reverse=True)
print (list2)
list1.clear()
print (list1)
list1=list2.copy()
print (list1)
2. 元组
#!/usr/bin/python3
tup1 = (12, 34.56)
tup2 = ('abc' , 'xyz' )
tup3 = tup1 + tup2
print (tup3)
#!/usr/bin/python3
tup = ('Google' , 'Runoob' , 1997, 2000)
print (tup)
del tup
print ("删除后的元组 tup : " )
print (tup)
关于元组是不可变的
所谓元组的不可变指的是元组所指向的内存中的内容不可变。
>>> tup = ('r' , 'u' , 'n' , 'o' , 'o' , 'b' )
>>> tup[0] = 'g'
Traceback (most recent call last):
File "<stdin>" , line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> id (tup)
4440687904
>>> tup = (1,2,3)
>>> id (tup)
4441088800
从以上实例可以看出,重新赋值的元组 tup,绑定到新的对象了,不是修改了原来的对象。
元组内置函数
序号
方法及描述
实例
1
len(tuple) 计算元组元素个数。
>>> tuple1 = ('Google', 'Runoob', 'Taobao') >>> len(tuple1) 3 >>>
2
max(tuple) 返回元组中元素最大值。
>>> tuple2 = ('5', '4', '8') >>> max(tuple2) '8' >>>
3
min(tuple) 返回元组中元素最小值。
>>> tuple2 = ('5', '4', '8') >>> min(tuple2) '4' >>>
4
tuple(iterable) 将可迭代系列转换为元组。
>>> list1= ['Google', 'Taobao', 'Runoob', 'Baidu'] >>> tuple1=tuple(list1) >>> tuple1 ('Google', 'Taobao', 'Runoob', 'Baidu')
3. 字典
1)删除字典
#!/usr/bin/python3
tinydict = {'Name' : 'Runoob' , 'Age' : 7, 'Class' : 'First' }
del tinydict['Name' ]
tinydict.clear()
del tinydict
print ("tinydict['Age']: " , tinydict['Age' ])
print ("tinydict['School']: " , tinydict['School' ])
2)字典键的特性
不允许同一键值出现两次,如果同一键值被赋予两次值,则后一个会被记住
键必须是不可变的,所以可以是字符串、数字、元组,而列表不行
3)字典的函数
序号
函数及描述
1
dict.clear()删除字典内所有元素
2
dict.copy()返回一个字典的浅复制
3
dict.fromkeys()创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
4
dict.get(key, default=None)返回指定键的值,如果键不在字典中返回 default 设置的默认值
5
key in dict如果键在字典dict里返回true,否则返回false
6
dict.items()以列表返回一个视图对象
7
dict.keys()返回一个视图对象
8
dict.setdefault(key, default=None)和get()类似, 但如果键不存在于字典中,将会添加键并将值设为default
9
dict1.update(dict2)把字典dict2的键/值对更新到dict里
10
dict.values()返回一个视图对象
11
pop(key[,default])删除字典 key(键)所对应的值,返回被删除的值。
12
popitem()返回并删除字典中的最后一对键和值。
字典直接赋值和copy的区别
dict1={"user" :"jiaxing" ,"sex" :"man" ,"num" :[1,2,3]}
dict2=dict1
dict3=dict1.copy()
dict1['user' ]="supershy"
dict1['num' ].remove(1)
print (dict1)
print (dict2)
print (dict3)
>>输出:
{'user' : 'supershy' , 'sex' : 'man' , 'num' : [2, 3]}
{'user' : 'supershy' , 'sex' : 'man' , 'num' : [2, 3]}
{'user' : 'jiaxing' , 'sex' : 'man' , 'num' : [2, 3]}
实例中 dict2 其实是 dict1 的引用(别名),所以输出结果都是一致的,dict3 父对象进行了深拷贝,不会随dict1 修改而修改,子对象是浅拷贝所以随 dict1 的修改而修改。
dict.fromkeys()
Python 字典 fromkeys() 函数用于创建一个新字典,以序列 seq 中元素做字典的键,value 为字典所有键对应的初始值。
seq =('user' ,'name' ,'sex' )
val='2'
dict1=dict.fromkeys(seq )
dict2=dict.fromkeys(seq ,val)
print (dict1)
print (dict2)
>>输出:
{'user' : None, 'name' : None, 'sex' : None}
{'user' : '2' , 'name' : '2' , 'sex' : '2' }
dict.get()
返回指定键的值,如果键不在字典中返回 default 设置的默认值
dict1={'name' :'jiaxing' ,'age' :22}
print (dict1.get('name' ,'没有这个键' ))
print (dict1.get('sex' ,'没有这个键' ))
tinydict = {'Name' : 'Runoob' , 'Age' : 27, 'student' :{'stu_name' :'jiaxing' }}
print (tinydict.get('student' ,{}).get('stu_name' ))
dict.items()、dict.keys()、dict.values()
Python 字典 items() 方法以列表返回视图对象,是一个可遍历的key/value 对。
dict.keys()、dict.values()和 dict.items() 返回的都是视图对象( view objects),提供了字典实体的动态视图,这就意味着字典改变,视图也会跟着变化。
视图对象不是列表,不支持索引,可以使用 list() 来转换为列表。
我们不能对视图对象进行任何的修改,因为字典的视图对象都是只读的。
dict1={'name' :'jiaxing' ,'age' :22}
print (dict1.items())
print (dict1.keys())
print (dict1.values())
>>输出:
dict_items([('name' , 'jiaxing' ), ('age' , 22)])
dict_keys(['name' , 'age' ])
dict_values(['jiaxing' , 22])
dict.setdefault()
Python 字典 setdefault() 方法和 get()方法类似, 如果键不存在于字典中,将会添加键并将值设为默认值。
dict1={'name' :'jiaxing' ,'age' :22}
print (dict1.setdefault('name' ))
print (dict1.setdefault('sex' ,None))
print (dict1)
>>输出:
jiaxing
None
{'name' : 'jiaxing' , 'age' : 22, 'sex' : None}
dict.update()
Python 字典 update() 函数把字典参数 dict2 的 key/value(键/值) 对更新到字典 dict1 里。
dict1={'name' :'jiaxing' ,'age' :22}
dict2={'sex' :'man' ,'hobby' :'game' }
dict1.update(dict2)
print (dict1)
>>输出:
{'name' : 'jiaxing' , 'age' : 22, 'sex' : 'man' , 'hobby' : 'game' }
dict.pop()
Python 字典 pop() 方法删除字典 key(键)所对应的值,返回被删除的值。
dict1={'name' :'jiaxing' ,'age' :22}
dict2={'sex' :'man' ,'hobby' :'game' }
element=dict2.pop('sex' )
print (element)
print (dict2)
>>输出:
man
{'hobby' : 'game' }
dict.item()
Python 字典 popitem() 方法随机返回并删除字典中的最后一对键和值。
如果字典已经为空,却调用了此方法,就报出 KeyError 异常。
#!/usr/bin/python3
site= {'name' : '菜鸟教程' , 'alexa' : 10000, 'url' : 'www.runoob.com' }
result = site.popitem()
print ('返回值 = ' , result)
print ('site = ' , site)
site['nickname' ] = 'Runoob'
print ('site = ' , site)
result = site.popitem()
print ('返回值 = ' , result)
print ('site = ' , site)
>>输出:
返回值 = ('url' , 'www.runoob.com' )
site = {'name' : '菜鸟教程' , 'alexa' : 10000}
site = {'name' : '菜鸟教程' , 'alexa' : 10000, 'nickname' : 'Runoob' }
返回值 = ('nickname' , 'Runoob' )
site = {'name' : '菜鸟教程' , 'alexa' : 10000}
4)字典遍历
a={'name' :'gaojiaxing' ,'age' :20}
for key in a.keys():
print (key)
for value in a.values():
print (value)
for key,value in a.items():
print (f"key:{key} value:{value}" )
a={'gaojiaxing' :20,
'supershy' :20
}
for value in set (a.values()):
print (value)
4. 字符串
python会将非空字符串解读为True,也可以用None作为占位符
name=''
if name:
print (name)
else :
print ('no name' )
age=None
if age:
print (age)
else :
print ('no age' )
1)字符串函数
序号
方法及描述
1
capitalize()将字符串的第一个字符转换为大写
2
center(width, fillchar)返回一个指定的宽度 width 居中的字符串,fillchar 为填充的字符,默认为空格。
3
count(str, beg= 0,end=len(string)) 返回 str 在 string 里面出现的次数,如果 beg 或者 end 指定则返回指定范围内 str 出现的次数
4
bytes.decode(encoding="utf-8", errors="strict") Python3 中没有 decode 方法,但我们可以使用 bytes 对象的 decode() 方法来解码给定的 bytes 对象,这个 bytes 对象可以由 str.encode() 来编码返回。
5
encode(encoding='UTF-8',errors='strict')以 encoding 指定的编码格式编码字符串,如果出错默认报一个ValueError 的异常,除非 errors 指定的是'ignore'或者'replace'
6
str.endswith(suffix[, start[, end]]) 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回 True,否则返回 False。可选参数 "start" 与 "end" 为检索字符串的开始与结束位置。
7
expandtabs(tabsize=8)把字符串 string 中的 tab 符号转为空格,tab 符号默认的空格数是 8 。
8
find(str, beg=0, end=len(string))检测 str 是否包含在字符串中,如果指定范围 beg 和 end ,则检查是否包含在指定范围内,如果包含返回开始的索引值,否则返回-1
9
index(str, beg=0, end=len(string)) 跟find()方法一样,只不过如果str不在字符串中会报一个异常。
10
isalnum()检查字符串是否由字母和数字组成,即字符串中的所有字符都是字母或数字。如果字符串至少有一个字符,并且所有字符都是字母或数字,则返回 True;否则返回 False。
11
isalpha()如果字符串至少有一个字符并且所有字符都是字母或中文字则返回 True, 否则返回 False
12
isdigit()如果字符串只包含数字则返回 True 否则返回 False.
13
islower()如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是小写,则返回 True,否则返回 False
14
isnumeric()如果字符串中只包含数字字符,则返回 True,否则返回 False
15
isspace()如果字符串中只包含空白,则返回 True,否则返回 False.
16
istitle()如果字符串是标题化的(见 title())则返回 True,否则返回 False
17
isupper()如果字符串中包含至少一个区分大小写的字符,并且所有这些(区分大小写的)字符都是大写,则返回 True,否则返回 False
18
join(seq) 以指定字符串作为分隔符,将 seq 中所有的元素(的字符串表示)合并为一个新的字符串
19
len(string)返回字符串长度
20
ljust(width[, fillchar]) 返回一个原字符串左对齐,并使用 fillchar 填充至长度 width 的新字符串,fillchar 默认为空格。
21
lower()转换字符串中所有大写字符为小写.
22
lstrip()截掉字符串左边的空格或指定字符。
23
maketrans()创建字符映射的转换表,对于接受两个参数的最简单的调用方式,第一个参数是字符串,表示需要转换的字符,第二个参数也是字符串表示转换的目标。
24
max(str)返回字符串 str 中最大的字母。
25
min(str)返回字符串 str 中最小的字母。
26
replace(old, new [, max])把 将字符串中的 old 替换成 new,如果 max 指定,则替换不超过 max 次。
27
rfind(str, beg=0,end=len(string))类似于 find()函数,不过是从右边开始查找.
28
rindex( str, beg=0, end=len(string))类似于 index(),不过是从右边开始.
29
rjust(width,[, fillchar])返回一个原字符串右对齐,并使用fillchar(默认空格)填充至长度 width 的新字符串
30
rstrip()删除字符串末尾的空格或指定字符。
31
split(str="", num=string.count(str)) 以 str 为分隔符截取字符串,如果 num 有指定值,则仅截取 num+1 个子字符串
32
splitlines([keepends])按照行('\r', '\r\n', \n')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
33
startswith(substr, beg=0,end=len(string))检查字符串是否是以指定子字符串 substr 开头,是则返回 True,否则返回 False。如果beg 和 end 指定值,则在指定范围内检查。
34
strip([chars]) 在字符串上执行 lstrip()和 rstrip()
35
swapcase()将字符串中大写转换为小写,小写转换为大写
36
title() 返回"标题化"的字符串,就是说所有单词都是以大写开始,其余字母均为小写(见 istitle())
37
translate(table, deletechars="")根据 table 给出的表(包含 256 个字符)转换 string 的字符, 要过滤掉的字符放到 deletechars 参数中
38
upper()转换字符串中的小写字母为大写
39
zfill (width)返回长度为 width 的字符串,原字符串右对齐,前面填充0
40
isdecimal()检查字符串是否只包含十进制字符,如果是返回 true,否则返回 false。
41
format() 字符串格式化工具
42
readline() 每次只读取一行
43
readlines() 一次性读取文件中所有行,并返回一个列表,文件中一行代表列表中一个元素
str1='jiaxing'
str2='gao\njia\rxing'
str3='supershy666嘉'
str4='123'
str5='Gao'
str6='五'
str7=' '
str8='GAO'
str9='-'
str10 = "this is string example....wow!!!"
list1=['g' ,'a' ,'o' ,'j' ,'i' ,'a' ,'x' ,'i' ,'n' ,'g' ]
print (str1.capitalize())
print (str1.upper())
print (str1.center(50,'*' ))
print (str1.count('i' ))
print (str1.count('i' ,0,4))
print (str1.endswith('xing' ))
print (str1.endswith('xing' ,3,7))
print (str2)
print (str2.expandtabs())
print (str2.expandtabs(3))
print (str1.find('xing' ))
print (str1.find('xing' ,5,7))
print (str1.rfind('xing' ))
print (str1.rfind('xing' ,5,7))
print (str1.index('xing' ))
print (str1.rindex('xing' ))
print (str1.isalnum())
print (str2.isalnum())
print (str3.isalnum())
print (str1.isalpha())
print (str2.isalpha())
print (str3.isalpha())
print (str1.isdigit())
print (str2.isdigit())
print (str3.isdigit())
print (str4.isdigit())
print (str1.islower())
print (str4.islower())
print (str5.islower())
print (str4.isnumeric())
print (str6.isnumeric())
print (str7.isspace())
print (str5.istitle())
print (str5.isupper())
print (str8.isupper())
print (str7.join(str1))
print (str9.join(str1))
print (str9.join(list1))
print (str1.ljust(50,'*' ))
print (str1.rjust(50,'*' ))
print (str1.lstrip('jia' ))
print (str1.rstrip('xing' ))
print (str1.strip('i' ))
mytab=str1.maketrans('j' ,'x' )
print (str1.translate(mytab))
print (str1.replace('i' ,'a' ,1))
print (str1.replace('jia' ,'gao' ))
print (str10.split())
print (str1.split('i' ))
print (str1.split('i' ,1))
print (str2.splitlines())
print (str2.splitlines(True))
print (str2)
print (str1.startswith('j' ))
print (str1.startswith('x' ,3,6))
print (str5.swapcase())
print (str1.zfill(50))
print (str4.isdecimal())
format / f"string" / %s % ()区别
从性能角度看,f-string 是最快的,其次是 str.format(),最后是 % 操作符。这是因为 f-string 是在运行时直接解析的,而其他两种方式需要更多的中间步骤。
从 Python 3.6 开始,引入了 f-strings,这是一种更简洁的字符串格式化方法,语法更直观
format
1)基本用法
s = "Hello, {}!" .format("world" )
print (s)
2)指定位置
print ('{0} and {1}' .format('spam' , 'eggs' ))
spam and eggs
print ('{1} and {0}' .format('spam' , 'eggs' ))
eggs and spam
s = "{name} is {age} years old" .format(name="Alice" , age=30)
print (s)
3)格式化数字
s = "The value of pi is approximately {0:.3f}" .format(3.1415926)
print (s)
s = "The number is {0:04d}" .format(42)
print (s)
4)对齐和填充
s = "{:<10}" .format("hello" )
print (s)
s = "{:>10}" .format("hello" )
print (s)
s = "{:^10}" .format("hello" )
print (s)
s = "{:*^10}" .format("hello" )
print (s)
5)格式化日期
from datetime import datetime
now = datetime.now()
s = "Today is {:%Y-%m-%d %H:%M:%S}" .format(now)
print (s)
6)格式化复杂数据结构
person = {"name" : "Bob" , "age" : 25}
s = "Name: {0[name]}, Age: {0[age]}" .format(person)
print (s)
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice" , 30)
s = "Name: {0.name}, Age: {0.age}" .format(person)
print (s)
7)使用 f-strings(Python 3.6+)
从 Python 3.6 开始,引入了 f-strings,这是一种更简洁的字符串格式化方法,语法更直观:
name = "Alice"
age = 30
s = f"Name: {name}, Age: {age}"
print (s)
s = f"The value of pi is approximately {3.1415926:.3f}"
print (s)
match语句
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通