Python(二) 高级变量类型
想学简单的数据类型绕道
内容
- 列表
- 元组
- 字典
- 字符串
列表
List(列表) 是 Python 中使用 最频繁 的数据类型,在其他的语言中通常叫做 数组
- 和数组的区别: 一般在其他语言中的数组,一个数组只能存储一种数据类型
- python 的一个列表可以存储所有的数据类型的数据(但一般推荐还是一个列表存储一种数据类型的数据)定义 :
name_list = ["张三", "李四", "王五"]
常用方法 :
修改: name_list[0] = "王麻子" 查找: 根据内容查找下标 name_list.index("李四") 返回 1 如果找到没有内容则报错 增加: append 方法可以向列表末尾添加数据 name_list.append("王小二") insert 方法可以在列表指定索引位置插入数据 name_list.insert(1, "胡巴") extend 方法可以将其他列表的完整内容,追加到当前列表的末尾 name_list.extend("序列") 删除: remove 方法可以删除指定的元素 如果列表没有该元素,则报错 name_list.remove("123") pop 方法为弹出,弹出末尾,返回值为弹出的值,可以指定参数为下标 name_list.pop() 或 name_list.pop(1) clear 方法清空列表 name_list.clear() del 关键字 删除 del name_list[1] 排序: sort() 方法进行升序排序 name_list.sort() sort(reverse=True) 方法进行降序排序 name_list.sort(reverse=True) reverse() 方法倒序排序 name_list.reverse()
元组
- Tuple(元组)与列表类似,不同之处在于元组的元素不能修改
- 元组 表示多个元素组成的序列
- 元组 在 Python 开发中,有特定的应用场景
- 用于存储 一串 信息,数据之间使用 , 分隔
元组用 () 定义
定义:
name_tuple = ("张三", "李四", "王五")
空元组 : tuple = ()
一个元素的元组 : tuple = ("张三",)方法:
index 方法获取元素的下标count 获取元素在元组中出现的次数
- 元组 表示多个元素组成的序列
字典
- dictionary(字典)是除列表以外 Python 之中 最灵活 的数据类型
与列表的区别:
列表 是 有序 的对象集合
字典 是 无序 的对象集合- 字典用 {} 定义
- 字典使用 键值对 存储数据,键值对之间使用 , 分隔
- 键 key 是索引 值 value 是数据
- 键 和 值 之间使用 : 分隔
- 键必须是唯一的
- 值 可以取任何数据类型,但 键 只能使用 字符串、数字或 元组(不可变的)
- 字典用 {} 定义
常用方法 :
查找:
user_dictionary = {.....}value = user_dictionary["key"]
修改
user_dictionary["key"] = new_value增加
user_dictionary["new_key"] = new_value删除
user_dictionary.pop("key")
pop(key) 如果没有参数key,则报错
pop(key) 方法的返回值为 key 对应的 value
字符串
- 用来表示一串文字信息
- 表示 单引号 双引号 三引号(三个单引号或者三个双引号) 能够扩起多行信息
自然字符串
- 字符串前加r或R,可以让转义字符失效,原样输出
- 例如: str = r"hello \n world"
- 字符串前加r或R,可以让转义字符失效,原样输出
单双引号交错使用
html = "<a style='color:red'> hahaha </a>"
print(html)
常用方法 :
# title 首字母大写
name = "hehehe"
print(name.title())
Hehehe# upper 全部大写 lower 全部小写
name = "hehehe"
print(name.upper())
name123 = "HEHEHE"
print(name123.lower())
HEHEHE
hehehe# 字符串空格的删除 rstrip 删除尾部的所有空格 lstrip 删除前部的所有空格 strip 删除前后的所有空格
# 字符串空格的删除 rstrip 删除尾部的所有空格 lstrip 删除前部的所有空格 strip 删除前后的所有空格
date = " python "
print(date)
print(date.rstrip())
print(date.lstrip())
print(date.strip())python python
python
python# startwith 方法是用来测试字符串是否以给定字符串开始