一、字符串
字符串运算符与常用函数
- s.find(‘xxx’)
- s.rstrip()
- s.replace(‘xxx’,‘xxx’)
- s.endswith(‘xxx’)
- ‘xxx’.join(strlist)
- str[1:3]
二、列表 []
删除列表元素
list1 = [1, 2, 1997, 2000];
print list1;
del list1[2];
print "After deleting value at index 2 : "
print list1;
[1, 2, 1997, 2000]
After deleting value at index 2:
[1, 2, 2000]
Python 列表脚本操作符
Python 列表截取
L = ['spam', 'Spam', 'SPAM!']
Python 列表函数 & 方法
- cmp() 方法
cmp(list1, list2)
- 如果比较的元素是同类型的,则比较其值,返回结果。
- 如果两个元素不是同一种类型,则检查它们是否是数字。
list1 = [1, 2, 1997, 2000]; list2 = [1, 2, 1997, 2001]; print(cmp(list1, list2)); #-1
详情:https://www.w3cschool.cn/python/att-list-cmp.html
- max(list),min(list):返回列表元素最大/最小值。
- list(seq):将元组转换为列表
- list.append(obj):在列表末尾添加新的对象。
- list.count(obj):统计某个元素在列表中出现的次数。
- list.extend(seq):在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)。
- list.index(obj):从列表中找出某个值第一个匹配项的索引位置。
- list.insert(index, obj):将对象插入列表。
- list.pop(obj = list[-1]):移除列表中的一个元素(默认最后一个元素),并且返回该元素的值。
- list.remove(obj):移除列表中某个值的第一个匹配项。
- list.reverse():反向列表中元素。
- list.sort([func]):对原列表进行排序。
三、元组 ()
元组的元素不能修改。元组中只包含一个元素时,需要在元素后面添加逗号。
tup1 = (1,)
删除整个元组
tup = ('physics', 'chemistry', 1997, 2000);
del tup;
Python 元组函数 & 方法
- tuple(seq):将列表转换为元组。
四、字典 {}
删除字典元素
dict = {'Name': 'Pan', 'Age': 7, 'Class': 'First'};
del dict['Name']; # 删除键是'Name'的条目
dict.clear(); # 清空词典所有条目
del dict ; # 删除词典
- dict.clear() :删除字典内所有元素
- dict.copy() :返回一个字典的浅复制
- dict.fromkeys() :创建一个新字典,以序列seq中元素做字典的键,val为字典所有键对应的初始值
dict.get(key, default=None)
:返回指定键的值,如果值不在字典中返回default值dict.has_key(key)
:如果键在字典dict里返回true,否则返回false- dict.items() :以列表返回可遍历的(键, 值) 元组数组
dict.keys()
:以列表返回一个字典所有的键- dict.setdefault(key, default=None) :和 get() 类似, 但如果键不已经存在于字典中,将会添加键并将值设为default
- dict.update(dict2):把字典 dict2 的键/值对更新到 dict 里
dict.values()
:以列表返回字典中的所有值