1字典的内置方法
gf = {"name": "高圆圆", "age": 32}
(1) 创建字典
knowledge = ['语文', '数学', '英语']
scores = dict.fromkeys(knowledge, 60)
print(scores)
(2) 获取某键的值
print(gf.get("name")) # "高圆圆 get 就是提取键值的操作
(3) 更新键值:添加或更改
gf.update({"age": 18, "weight": "50kg"})
print(gf) # {'name': '高圆圆', 'age': 18, 'weight': '50kg'}
(4) 删除weight键值对
ret = gf.pop("weight") # 返回删除的值
print(gf)
(5) 遍历字典键值对(重点)
items = list(gf.items())
print(items)#输出结果:[('name','高圆圆'),('age',32)]
for k, v in gf.items():
print(k, v)
### (6)创建字典
courses = ["English","math","chinese"]
#自行创建字典
ret = dict.fromkeys(courses,_value:60)
print(ret)
d4 = {"x": 10, "y": 20}
l2 = [1, 2, d4]
# d4["z"] = 30
# print(l2)
l2[2]["y"] = 200#将l2中第三个元素所指向的字典里的元素值彻底改变。
l2[2] = [3,4]#将l2的第三个元素d4替换成新的列表,原字典d4不会发生改变,
print(d4)#{'x': 10, 'y': 20}
print(l2[2])#[3, 4]
2字符串的内置方法
(1) 字符串转大写:upper(),字符串转小写:lower()
s = "YuanHao"
print(s.upper()) # YUANHAO
print(s.lower()) # yuanhao
(2) 判断是否以xxx开头
name = "张三"
判断是不是姓张
print(name.startswith("张"))
(3) 判断是否以xxx结尾
url = "/xxx/yyy/zzz/a.png"
print(url.endswith("png"))
(4) find和index都是查找某子字符串的索引,find找不到返回-1,index找不到报错
print(name.find("三"))
print(name.index("三"))
(5) 去除两端空格或换行符\n
name = input("请输入姓名:")
print(name, len(name))
name = name.strip()
print(name, len(name))
(6) 判断某字符串是否全是数字
print("123".isdigit())
(7) split()和join()
cities = "天津 北京 上海 哈尔滨"
cities_list = cities.split(" ")
print("cities_list", cities_list)
print(len(cities_list))
ret = ",".join(cities_list)
print(ret) # "天津,北京,上海,哈尔滨
info = "yuan 19 180"
info_list = info.split(" ")
print(info_list[0])
print(info_list[1])
print(info_list[2])
(8) replace(): 子字符串替换
sentence = "PHP is the best language.PHP...PHP...PHP..."
new_sentence = sentence.replace("PHP", "Python")
print(new_sentence)
comments = "这个产品真棒!我非常喜欢。服务很差,不推荐购买。这个餐厅的食物质量太差了,味道不好。我对这次旅行的体验非常满意。这个电影真糟糕,剧情一团糟。这个景点真糟糕,再也不来了!"
comments = comments.replace("差", "").replace("不推荐", "").replace("糟糕", "***")
print(comments)
(9) count:计算字符串中某个子字符串出现的次数
print(sentence.count("PHP"))
标签:name,04,list,gf,l2,print,cities From: https://www.cnblogs.com/huhumarshal/p/18109369