元祖的定义
1 tu = (11,22,33,44,) 2 print(tu) # (11, 22, 33, 44) 3 4 tu = tuple((11,22,33,44,)) 5 print(tu) # (11, 22, 33, 44)
元祖的特性
1 # 可存放多个值 2 # 不可变【一级元素不可修改】 3 # 按照从左到右的顺序定义元祖,下标从0开始顺序访问,有序 4 # 元祖【一级元素】不可以进行增加、删除、修改操作
元祖的常用操作
索引
1 # 索引 2 I = ("egon","alex","seven","yuan") 3 print(I[0]) # egon 4 print(I[-1]) # yuan 5 print(I[-2]) # seven
切片
1 # 切片 2 I = ("egon","alex","seven","yuan") 3 print(I[1:3]) # ('alex', 'seven') 4 print(I[1:]) # ('alex', 'seven', 'yuan') 5 print(I[:3]) # ('egon', 'alex', 'seven') 6 print(I[1:-1]) # ('alex', 'seven') 7 print(I[:]) # ('egon', 'alex', 'seven', 'yuan') 8 print(I[::3]) # ('egon', 'yuan') 跨度为3 9 print(I[::-1]) # ('yuan', 'seven', 'alex', 'egon') 反转了
长度
1 # 长度 2 I = ("egon","alex","seven","yuan") 3 print(len(I)) # 4
包含
1 # 包含 2 I = ("egon","alex","seven","yuan") 3 if "yuan" in I: 4 print("ok") # ok
循环
1 # 循环 2 I = ("egon","alex","seven","yuan") 3 for i in I: 4 print(i)
拼接
1 I = ("egon","alex","seven","yuan") 2 s = "_".join(I) 3 print(s) # egon_alex_seven_yuan
注:元祖、列表中的元素,全部为字符串时可以用join拼接为字符串,否则只能使用for循环拼接
字符串只能通过索引去取值、不能修改