这里所说的公共操作指的是之前学过的序列基本上都支持的一些操作,主要分成三大块来讲解,第一块是运算符;第二块是公共方法;第三块是容器类型转换。

一、运算符

运算符

描述

支持的容器类型

+

合并

字符串、列表、元组

*

复制

字符串、列表、元组

in

元素是否存在

字符串、列表、元组、字典

not in

元素是否不存在

字符串、列表、元组、字典

二、运算符加号 +(合并)

代码体验:

str1 = 'aaa'
str2 = 'bbb'

list1 = [1, 2]
list2 = [3, 4]

tuple1 = (10, 20)
tuple2 = (30, 40)

# 字符串合并
print(str1 + str2)
# 列表合并
print(list1 + list2)
# 元组合并
print(tuple1 + tuple2)

执行结果:

 

三、运算符乘号 *(复制)

代码体验:

str1 = 'aaa'
list1 = [1, 2]
tuple1 = ('hello',)

# 字符串复制
print(str1 * 3)
# 列表复制
print(list1 * 5)
# 元组复制
print(tuple1 * 5)

执行结果:

 

四、判断数据是否存在(in 、 not in)

代码体验:

str1 = 'abcd'
list1 = [1, 2, 3, 4]
tuple1 = (10, 20, 30, 40)
dict1 = {'name': 'Python自学网', 'age': 30}

# 字符串 - 字符b是否存在
print('a' in str1)  # True
print('a' not in str1)   # False
# 列表 - 数据2是否存在
print(2 in list1)  # True
print(2  not in list1)  # False
# 元组 - 数据20是否存在
print(20 in tuple1)   # True
print(20  not in tuple1)  # False

# 字典 - 数据age是否存在
print('age' in dict1)   # True
print('age' not in dict1)  # False

print('age' in dict1.keys())  # True
print('age' in dict1.values())  # False

执行结果:

 

以上就是Python公共操作中的运算符讲解,自己可以多写一些代码尝试一下,不过看上面的代码演示应该也是可以完全理解的。更多全面的Python讲解可以移步去Python自学网。

更多推荐

Python公共操作之运算符(加号、乘号、判断数据是否存在)