Python基础补充部分
- 编程知识
- 2023-06-07
- 2
本文将从以下几个方面对Python基础补充部分做详细的阐述,包括字符串、列表、字典和文件操作。每个方面都将有2-3个自然段,帮助读者更好地理解和应用Python。
一、字符串
1、字符串基本操作
# 字符串拼接 str1 = 'Hello' str2 = 'World' str3 = str1 + ' ' + str2 print(str3) # Hello World # 字符串截取 str4 = 'Python' print(str4[2:4]) # th # 字符串替换 str5 = 'I love Python' print(str5.replace('Python', 'Java')) # I love Java
2、字符串格式化
# 格式化整数 num = 666 print('num is %d' % num) # 格式化浮点数 fl = 1.23 print('fl is %.2f' % fl) # 格式化字符串 name = 'Tom' age = 18 print('%s is %d years old' % (name, age))
二、列表
1、列表基本操作
# 列表添加元素 list1 = [1, 2, 3] list1.append(4) print(list1) # [1, 2, 3, 4] # 列表删除元素 list2 = ['a', 'b', 'c'] list2.remove('b') print(list2) # ['a', 'c'] # 列表排序 list3 = [5, 3, 1, 4, 2] list3.sort() print(list3) # [1, 2, 3, 4, 5]
2、列表生成式
# 带条件的列表生成式 list4 = [i for i in range(1, 11) if i % 2 == 0] print(list4) # [2, 4, 6, 8, 10] # 嵌套列表生成式 list5 = [[i, j] for i in range(1, 3) for j in range(3, 5)] print(list5) # [[1, 3], [1, 4], [2, 3], [2, 4]]
三、字典
1、字典基本操作
# 字典添加元素 dict1 = {'name': 'Tom', 'age': 18} dict1['sex'] = 'male' print(dict1) # {'name': 'Tom', 'age': 18, 'sex': 'male'} # 字典删除元素 dict2 = {'name': 'John', 'age': 20} del dict2['age'] print(dict2) # {'name': 'John'} # 字典遍历 dict3 = {'name': 'Lucy', 'age': 25, 'sex': 'female'} for key in dict3: print(key, dict3[key])
2、字典推导式
# 字典推导式 list6 = ['a', 'b', 'c'] dict4 = {i: len(i) for i in list6} print(dict4) # {'a': 1, 'b': 1, 'c': 1}
四、文件操作
1、文件读取
# 读取文本文件 with open('test.txt') as f: lines = f.readlines() for line in lines: print(line.strip()) # 读取二进制文件 with open('test.jpg', 'rb') as f: data = f.read()
2、文件写入
# 写入文本文件 with open('test.txt', 'w') as f: f.write('Hello Python') # 写入二进制文件 with open('test.jpg', 'wb') as f: f.write(data)
本文介绍了Python基础补充部分的字符串、列表、字典和文件操作,包括一些基本操作和推导式的使用,希望对读者能够有所帮助。