python学习笔记6
python学习笔记6
一、字符串的相关函数
-
capitalize
# 首字母大写,其余字母小写 s = 'liEvE' print(s.capitalize()) # Lieve -
swapcase
# 大小写反转 s = 'liEvE' print(s.swapcase()) # LIeVe -
title
# 每个单词的首字母大写 s = 'hello worlD' print(s.title()) # Hello World -
center
# 居中 s = 'helloworld' print(s.center(20)) # helloworld print(s.center(20,'*')) # *****helloworld***** -
find,index
# find通过元素找索引,找到就返回元素第一次出现的索引,找不到就返回-1 s = 'lieve' print(s.find('i')) # 1 print(s.find('e')) # 2 print(s.find('o')) # -1 # index通过元素找索引,找到就返回元素第一次出现的索引,找不到就报错 print(s.index('i')) # 1 print(s.index('e')) # 2 print(s.index('o')) # ValueError: substring not found
二、元组的相关函数
-
count
# 计算元组中指定元素出现的次数 tuple_1 = (1,2,3,3,2,23,3,3) print(tuple_1.count(3)) # 4 -
index
# 用法和字符串的index一样,返回值也一样
三、列表的相关函数
-
count和index
# 用法和前面的一致 -
sort、reverse
# 一般而言,只有给数字排序才有意义 # 可以原地修改 li_1 = [5,4,2,8,21,4,5,67] li_1.sort() # 默认从小到大排序 # li_1.sort(reverse=True) # 从大到小排序 print(li_1) # [2, 4, 4, 5, 5, 8, 21, 67] # 列表元素反转 li_1.reverse() print(li_1) # [67, 5, 4, 21, 8, 2, 4, 5] -
列表的相加与相乘
li_1 = [1,2,3] li_2 = ['a','b','c'] print(li_1+li_2) # [1, 2, 3, 'a', 'b', 'c'] print(li_1*3) # [1, 2, 3, 1, 2, 3, 1, 2, 3] -
注意!在对一个列表进行循环的过程中,如果对列表进行改变,则很容易引起错误。
四、字典的相关函数
-
fromkeys
# fromkeys函数的第一个参数要求是一个可迭代对象。值共用一个。 dict_1 = dict.fromkeys('abc',100) print(dict_1) # {'a': 100, 'b': 100, 'c': 100} # 特殊情况 dict_2 = dict.fromkeys('abc',[]) print(dict_2) # {'a': [], 'b': [], 'c': []} dict_2['a'].append(666) print(dict_2) # {'a': [666], 'b': [666], 'c': [666]} -
注意!在对一个字典的键进行循环的过程中,如果对字典进行改变,也很容易引起错误。
五、所有数据都可以转化成bool值
# 转换成bool值为False的数据类型有:
# '', 0, (), [], {}, set(), None
六、计算机编码知识
- 在计算机内存中,统一使用Unicode编码,但当需要将数据用于网络传输或者存储到硬盘时,必须以非Unicode编码。
- 编码函数encode,解码函数decode

浙公网安备 33010602011771号