元组的基本使用
创建元组
元组内的元素可以是不同类型,且元组不可修改
info_tuple = ("zhangsan",18,1.75)
# 取值和取索引
print(info_tuple[0])
# 已经知道数据的内容,希望知道该数据在元组中的索引
print(info_tuple.index("zhangsan"))
# 统计计数
print(info_tuple.count("zhangsan"))
# 统计元组中包含元素的个数
print(len(info_tuple))
注意创建只包含一个元素的元组需要加一个逗号
info_tuple(5,) # 因为元组和列表类似,以逗号隔开各个元素,但是不加逗号会使数据类型是int类型
格式化字符串的扩展
info_tuple = ("小明",21,1.85)
# 格式化字符串后面的`()`本质上就是元组
print("%s 年龄是%d,身高是%.2f" % info_tuple)
# 换种写法,将括号内的内容赋予一个变量
info_str = "%s 年龄是%d,身高是%.2f" % info_tuple
print(info_str)
输出为