在这里,我们将介绍以下Python元组练习,
创建和打印元组
将元组解包成字符串
创建一个包含字符串字母的元组
创建一个元组,其中包含字符串的首字母,但不包含首字母
反转元组
考虑以下程序,它包含所有上述练习。
''' 1) Creating & printing a tuple ''' cities = ("New Delhi", "Mumbai", "Indore") print("cities: ", cities) print("cities[0]: ", cities[0]) print("cities[1]: ", cities[1]) print("cities[2]: ", cities[2]) print() # 打印换行符 ''' 2) Unpacking the tuple into strings ''' str1, str2, str3 = cities print("str1: ", str1) print("str2: ", str2) print("str3: ", str3) print() # 打印换行符 ''' 3) Create a tuple containing the letters of a string ''' tpl = tuple("Hello") print("tpl: ", tpl) print() # 打印换行符 ''' 4) Creating a tuple containing all but the first letter of a string ''' # 通过直接字符串 tpl1 = tuple("Hello"[1:]) print("tpl1: ", tpl1) # 通过字符串变量 string = "Hello" tpl2 = tuple(string[1:]) print("tpl2: ", tpl2) print() # 打印换行符 ''' 5) Reversing a tuple ''' name = ("Shivang", "Radib", "Preeti") # 使用切片技术 rev_name = name[::-1] print("name: ", name) print("rev_name: ", rev_name)
输出结果
cities: ('New Delhi', 'Mumbai', 'Indore') cities[0]: New Delhi cities[1]: Mumbai cities[2]: Indore str1: New Delhi str2: Mumbai str3: Indore tpl: ('H', 'e', 'l', 'l', 'o') tpl1: ('e', 'l', 'l', 'o') tpl2: ('e', 'l', 'l', 'o') name: ('Shivang', 'Radib', 'Preeti') rev_name: ('Preeti', 'Radib', 'Shivang')