基础数据类型补充
str: 不可变
1.1 首字母大写:
name = "xieyulin"
print(name.capitalize())
1.2 每个单词首字母大写
name = "yulin%yilin"
print(name.title())
1.3 大小写反转
name = 'Yulin'
print(name.swapcase())
1.4 居中 -- 填充
name = "yulin"
print(name.center(20, "-"))
1.5 查找 -- 从左向右 只查找一个
name = "yulinlin"
print(name.find("l"))
print(name.find("b")) # find查找不存在的返回-1
print(name.index("l"))
print(name.index("b")) # index查找不存在的就报错
1.6 拼接
name = "yulin"
print("_".join(name)) # y_u_l_i_n
1.7 格式化:%s f .format()
name = "xieyulin {},{},{}"
print(name.format(4, 5, 0)) # 按照顺序位置进行填充 xieyulin 4,5,0
name = "xieyulin {2},{0},{1}"
print(name.format("a", "b", "c")) # 按照索引值进行填充 xieyulin c,a,b
name = "xieyulin {a},{b},{c}"
print(name.format(a=1, c=67, b=21)) # 按照关键字进行填充 xieyulin 1,21,67
+ * 开辟新的空间
name = "yulin"
name1 = "yilin"
print(id(name))
print(id(name1))
print(id(name + name1))
list:
定义方式:
print(list("1234")) # ['1', '2', '3', '4']
其他方法:
lst = [1, 234, 4523, 121, 534, 7784, 23, 453]
lst.sort() # 排序(升序)
print(lst)
lst = ["你好", "我好", "大家好"]
lst.sort() # 排序(默认升序)
print(lst)
lst = [1, 2, 3, 4, 5, 6, 7]
lst.reverse() # 反转
print(lst) # [7, 6, 5, 4, 3, 2, 1]
lst = [1, 2, 3, 4, 5, 6, 7]
print(lst[::-1]) # # 反转
lst = [1, 2, 3, 4, 5, 6, 7]
lst.sort()
lst.reverse()
print(lst) # 降序
lst = [1, 2, 3, 4, 5, 6, 7]
lst.sort(reverse=True) # 降序
print(lst)
面试题:
lst = [[]]
new_lst = lst * 5
new_lst[0].append(10)
print(new_lst)
lst = [1, []]
new_lst = lst * 5
new_lst[0] = 10
print(new_lst)
lst = [1, []]
new_lst = lst * 5
new_lst[1] = 10
print(new_lst)
lst = [1, 2, 3, 4, 5]
lst1 = [6, 7, 8, 9]
合并:
方式一:
lst.extend(lst1)
print(lst)
方式二:
print(lst+lst1)
new_lst = lst * 5
print(id(new_lst[0]), id(new_lst[-5]))
tuple:
tu = (1) # 数据类型是()中数据的本身
print(type(tu))
tu = (1,) # (1,)是元组
print(type(tu))
元组可以 + * 不可变共用,可变也共用
dict:
定义一个字典:
print(dict(k1=1, k2=2))
随即删除:popitem python3.6后默认删除最后一个
dic = {"key1": 1, "key2": 2, "key3": 3}
print(dic.popitem()) # 返回的是被删除的键值对(键,值)
print(dic)
面试题:
dic = {}
dic1 = dic.fromkeys("123", [23]) # 批量添加键值对{"1":[23],"2":[23],"3":[23]}
print(dic)
print(dic1)
dic = dict.fromkeys("123", [23]) # 批量添加键值对"键是可迭代对象",值会被共用
dic["1"].append(5)
print(dic)
set:
set() -- 空集合
{} -- 空字典
定义集合:
set("yulin") # 迭代添加的
bool:False
数字:0
字符串:""
列表:[]
元组:()
字典:{}
集合:set()
其他:None
机智:3 > 10
数据类型之间的转换
list-tuple
tuple-list
str-list
name = "yulin"
print(name.split())
list-str
lst = ["1", "2", "3"]
print(''.join(lst))
dict-str
dic = {"1": 1}
print(str(dic), type(str(dic)))

浙公网安备 33010602011771号