1、 f-string(3.6)
-
格式化字符串、格式化浮点数、格式化字符串宽度
name = "ndream" age = 18 print(f'{name} is {age} years old.') val = 12.3432 print(f'{val:.2f}') # 保留两位小数 print(f'{val:08}') # 格式化字符串宽度为5,不够补0 print(f'{val:8}) # 格式化字符串宽度为5,不够不空格
ndream is 18 years old. 012.3432 12.3432
-
{ }
中可以使用表达式times = 10 hour = 2 print(f'total time is {times * hour}')
total time is 20
-
格式化日期
import datetime now = datetime.datetime.now() print(f'{now:%Y-%m-%d %H:%M}')
2、海象运算符(3.8)
-
可以实现
c++
的while (cin >> i)
,输入任意个字符while (i:=input('please input i: ')):
3、检查列表是否为空(集合、列表、元组、字典均可使用)
-
可以直接使用
if
判断nums = [1, 2, 3] if nums: print('not empty') else: print('empty')
not empty
4、解构赋值(集合、列表、元组、字典均可解构)
-
将元组同时赋值给多个不同的变量
nums = (1, 2, 3) x1, x2, x3 = nums print(f'x1:{x1} x2:{x2} x3:{x3}') names = {1:'Bob', 2:'Steve', 3:'Ben'} x1, x2, x3 = names.items() print(f'x1:{x1} x2:{x2} x3:{x3}')
x1:1 x2:2 x3:3 x1:(1, 'Bob') x2:(2, 'Steve') x3:(3, 'Ben')
5、一个索引用于多个列表
-
将两个列表中的值做乘法操作
hourly_wage = [35, 40, 45, 40, 60] hours = [8, 9, 10, 6, 5] wages = [] for value1, value2 in zip(hourly_wage, hours): wages.append(value1 * value2)
6、获取列表索引
-
普通的方法是(
{ }
集合无下标)nums = [1, 3, 5] for i in range(len(nums)): print(f'{i}: {nums[i]}')
-
看起来比较专业的做法是
nums = [1, 3, 5] for index, num in enumerate(nums): print(f'{index}: {num}')
7、自动关闭文件
-
可以避免使用完文件之后忘记关闭
with open('data.txt', 'w') as f: f.write('hello world')