【Python】字符串操作

1.取3位小数

num = 3.1415926
# 方法1:使用 round() 函数
result = round(num, 3)  # 3.142(四舍五入)

# 方法2:%格式化
result = "%.3f" % num  # '3.142'(字符串)

# 方法3:format()
result = "{:.3f}".format(num)  # '3.142'

# 方法4:f-string(Python 3.6+)
result = f"{num:.3f}"  # '3.142'

# 使用 or 0 将 None 转换为 0,如果读取的列表为空值,在计算时将其转换为0
highway = (dict_01["402"][4] or 0) + (dict_01["404"][4] or 0)
#在循环中汇总数字时,遇到空值转化为0
count_ej12_1 += float(row[7]) if row[7] is not None else 0.0 
 

 

posted @ 2025-05-17 16:26  山鬼谣`  阅读(17)  评论(0)    收藏  举报