文章目录
序列的公共方法
公共操作指的就是所学过的数据序列基本上都支持的操作。
以下是总结内容:
一、运算符
运算符 | 描述 | 支持的容器类型 |
---|---|---|
+ | 合并 | 字符串、列表、元组 |
* | 复制 | 字符串、列表、元组 |
in | 元素是否存在 | 字符串、列表、元组、字典 |
not in | 元素是否不存在 | 字符串、列表、元组、字典 |
@1.+
加号
+
可以将两个序列拼接为一个序列。
# 1. 字符串 `+`号
str1 = 'aa'
str2 = 'bb'
str3 = str1 + str2
print(str3) # aabb
# 2. 列表 `+`号
list1 = [1, 2]
list2 = [10, 20]
list3 = list1 + list2
print(list3) # [1, 2, 10, 20]
# 3. 元组 `+`号
t1 = (100, 200)
t2 = (10, 20)
t3 = t1 + t2
print(t3) # (100, 200, 10, 20)
# 4.字典 `+`号
# 结果:TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
dict1 = {
'name': 'Python'}
dict2 = {
'age': 30}
dict3 = dict1 + dict2
print(dict3) # 异常
@2.*
乘号
可以将序列重复指定的次数。
# 1. 字符串
# 结果:----------
print('-' * 10)
# 2. 列表
# 结果:['hello', 'hello', 'hello', 'hello']
list1 = ['hello']
print(list1 * 4)
# 3. 元组
# 结果:('world', 'world', 'world', 'world')
t1 = ('world',)
print(t1 * 4)
# 字典
# 结果:TypeError: unsupported operand type(s) for *: 'dict' and 'int'
dict1 = {
'name': 'Python'}
print(dict1 * 4) # 异常
@3.in
或not in
# 1. 字符串
print('a' in 'abcd') # True
print('a' in 'hijk') # False
print('a' not in 'abcd') # False
print('a' not in 'hijk') # True
# 2. 列表