一.字典(dict)

1.字典中可以存储任意类型的对象,数据采用键值对存储,键是唯一的,没有顺序(无序)
多用于保存物体的详细信息
键可以用数字,字符串,元组充当,不能用列表,否则就会报错
2.定义及格式:字典名={键(key) : 值(value) ,
键(key) : 值(value) ,
键(key) : 值(value)
}

3.增/删/改/查/合并
(1)增加或者创建

dict[“key”] = value (增加相同的键会覆盖原有的数据)


(2)删除

删除键:
 dict.pop(“key”)
 del dict[“key”]
 删除字典:
 del dict
 清空字典:
 dict.clear()


(3)修改

dict[“key”] = value


(4)查看

print(字典名)
 dict[“key”]


(5)合并

dict1 = {“name” : “wang”
 “age” : 18
 “height” : 1.77}
 dict2 = {“tel” : 8888888
 “email” : 66666666@qq.com}
 dict1.update(dict2)

(6)迭代遍历

dict = {"name" : "wang"
             "age" : 18
             "height" : 1.77}
    for my_dict in dict:
        print(my_dict)

(7)count和len()

dict.count()
 len(dict)

二.字符串

1.用"“或’'定义,为了和其他语言保持兼容性常采用”",字符串的存储采用有序,每个元素都有对应的角标或索引。

str = ’ “” ’


2.使用迭代遍历字符串时,会把字符串中的东西一个一个输出出来(竖排显示)
3.拆分与连接

str = “hello \t python \n nihao \t”
 拆分(split)
 str_list = str.split()
 连接(join)
 str = “,” join(str_list)


4.查找与替换

hello_str = “hello world”

1.判断是否以指定字符串开始
print(hello_str.startswith(“He”))

2.判断是否已指定的字符串结束
print(hello_str.endswith("d"))

3.查找指定的字符串
find:
print(hello_str.find("llo"))

find 查找指定的字符串,如果字符串不存在,会返回-1
print(hello_str.find("py"))

index:同样可以查找指定的字符串的索引(大串中查找小串的索引)
print(hello_str.index("llo"))

index查找指定的字符串,如果说字符串不存在,报错
print(hello_str.index("py"))

4.替换字符串

replace方法执行完成之后,会返回一个新的字符串
注意:使用replace不会修改原有的字符串的内容
print(hello_str.replace("world","python"))
print(hello_str)

5.文本对齐

poem = [“登鹳雀楼”,
 “王之涣”,
 “白日依山尽”,
 “黄河入海流”,
 “欲穷千里目”,
 “更下一层楼”]


center 方法时候:两个参数,一个width,另一个就是填充字符

for poem_str in poem:
 居中对齐:print("|%s|"%poem_str.center(10," “))
 左对齐:print(”|%s|" % poem_str.ljust(10, " “))
 右对齐:print(”|%s|" % poem_str.rjust(10, " “))


6.判断
1.判断空白字符 \t \n \r 回车

space_str = " a”
 print(space_str.isspace())

2.判断字符串中是否只包含数字: isdecimal()

1>.isdecimal
 num_str = “⑴”
 print(num_str.isdecimal())
 print(num_str.isdigit())

7.去除空白符号
strip()

三.完整的for循环

for num in [1,2,3]:
    print(num)

    if num == 2:
        break

else:
    #如果循环体内使用break退出了循环
    #else下方的代码不会被执行的

四.切片

切片方法适用于: 字符串、列表、元组
切片使用索引值来限定范围,从一个 大的字符串 中切出 小的字符串
列表和元组都是 有序 的集合,都能够 通过 索引值 获取到对应的数据
字典是一个 无序的集合,是使用 键值对 保存数据
格式:
字符串[开始索引:结束索引:步长] #可以省略开始索引和结束索引

str = “hello python”
 从头取到尾,步长为1
 print(str[::])
 从尾取到头
 print(str[::-1])