提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
字符串
遍历
s = r'Welcome to study'
for i in s:
print(i, s[i])
for i in range(len(s)):
print(i, s[i]) #'Welcome to study
for item in enumerate(s):
print(item) #返回下标和值
index,find,count
s = r'Welcome to study'
pos = s.index('s')
pos = s.index('s', 3,15) # 从指定位置中进行查找
pos = s1.index('oo')
s1 = 'noodle too'
pos = s.find('s', 3, 15)
pos = s.rfind('s') #找到最右边的下标
pos = s.lfind('s') #找到最左边的下标
pos = s.count('s', e) #e在s中出现的次数
upper,lower,swapcase,capitalize,title,hex
s = "abcdABCD abcdABCD"
new_s = s.upper() #将所有字母大写
new_s = s.lower() #将所有字母小写
new_s = s.swapcase() #将所有字母大小写反转
new_s = s.capitalize() #所有首字母大写
new_s = s.title() #所有单词首字母大写
print(hex(255)) #根据编码规则 获取字符对应的字节数据
isdigit,isalpha,isalnum
s = '1230abcd'
res = s.isdigit() #判断是否为纯数字
res = s.isalpha() #判断是否为纯字母
print('123abc比你好'.encode(encoding='utf-8').isalnum()) #判断是否为数字和字母组成
列表
append,insert,extend(添加)
nums = [23, 71, 29, 77, 83, 23, 14, 51, 79, 23]
res = nums.append(17) #在列表后添加
nums.insert(1, 80) #在指定下标添加
nums.extend(range(7, 100, 7))
pop,remove(删除),clear
value = nums.pop() #删除末尾元素
nums.remove(23) #删除首个为23的元素
nums.clear() #清空列表
count,copy
count = nums.count(23)
copy_nums = nums.copy()
推导式
nums = [1, 2, 3, 4, 5]
res = '+'.join([str(ele) for ele in nums]) #使用推导式将所有值连接在一起
pass_scores1 = [sc for sc in scores if sc >= 60] #找出大于60的值
元组
打包和解包
# 打包
a = 10, 22, 33, 45, 61
print(type(a), a) # <class 'tuple'> (10, 22, 33, 45, 61)
# 解包
a, b, c = 'xyz'
print(a, b, c) # 'x' 'y' 'z'
查找
print(len(t)) # 元组的长度
print(t.index(19)) # 获取元素第一次出现的位置
print(t.index(19, 5)) # 从下标5开始第一次出现的位置
set
集合是无序存储,无重复值
添加
s1 = {13, 27, 38}
s1.add(19)
移除
s1.remove(27) # 不是成员 会报错
s1.discard(27) # 不是成员 不做响应
s1.clear() # 清空
集合运算符
& 交集 把数据存储在一个新的集合中
| 并集 把数据存储在一个新的集合中
^ 对称差 把数据存储在一个新的集合中
- 差集 把数据存储在一个新的集合中
&= 交集 修改前者
|= 并集 修改前者
^= 对称差 修改前者
-= 差集 修改前者
> 判断后者是否为前者的真子集
>= 判断后者是否为前者的子集
< 判断前者是否为后者的真子集
<= 判断前者是否为后者的子集
== 判断两个集合数据是否一样
!= 判断两个集合数据是否不一样
in 判断元素是否包含在集合中
not in 判断元素是否不包含在集合中
id 获取地址
is 判断地址是否一致
not is 判断地址是否不止一致
dict
setdefault(添加)
键不存在 添加新的键值对
键若存在 不做任何反应
scores = {'语文': 78, '数学': 97, '英语': 82, '政治': 77}
scores.setdefault('化学', 78)
update
合并其他序列的元素,也可以更新值
scores.update({'历史': 77, '地理': 56})
delete(删除)
del scores['历史']
get,keys,values
变量名 = 字典数据.get(键)
键若存在 获取键对应的数据值
键若不存在 不会报错 返回的是None
value = scores.get('语文')
# 获取所有的键
all_keys = scores.keys()
#获取所有的值
all_values = scores.values()
推导式
# 成绩在60到80之间的 科目及其成绩信息
scores_6080 = {}
print({k: v for k, v in scores.items() if 60 <= v <= 80})