元组
定义一个元组
# 定义一个空元组
data = tuple()
print(data) # ()
print(type(data)) # <class 'tuple'>
data = ()
print(data) # ()
print(type(data)) # <class 'tuple'>
data = ("小满", 3)
print(data) # ('小满', 3)
print(type(data)) # <class 'tuple'>
# 可以 但是不建议
data = "小满", 3
print(data) # ('小满', 3)
print(type(data)) # <class 'tuple'>
元组的相加
number = (1, 2, 3, 4)
symbol = ("a", "b", "c", "d")
new_tuple = number + symbol
print(new_tuple) # (1, 2, 3, 4, 'a', 'b', 'c', 'd')
元组的相乘
base_tuple = ("小满", "最棒啦")
new_tuple = base_tuple * 3
print(new_tuple) # ('小满', '最棒啦', '小满', '最棒啦', '小满', '最棒啦')
元组的常用方法
元组无法增删改查,一般用来存放的数据基本上不会去做修改
count
data = ("小满", 3, "女", "小满")
print(data.count("小满")) # 2
index
data = ("小满", 3, "女", "小满")
print(data.index("小满")) # 0
元组的修改
元组是不支持增删改查的,不过可以先转成列表,修改好值之后,然后转成元组
my_tuple = ("小满", 3)
data = list(my_tuple)
data[0] = "王昭君"
new_tuple = tuple(data)
print(my_tuple) # ('小满', 3)
print(new_tuple) # ('王昭君', 3)