当前位置:  首页>> 技术小册>> Python合辑5-格式化字符串

Python f-string方法有个非常便捷的实现格式化百分数的操作方法。方法与浮点数格式化类似,但是要用%代替结尾的f。它会将原始数值乘以100并显示成有百分符号的固定格式。精度一样也是可以设定的。

  1. >>> total = 87
  2. >>> true_pos = 34
  3. >>> perc = true_pos / total
  4. >>> perc
  5. 0.39080459770114945
  6. >>> f"Percentage of true positive: {perc:%}"
  7. 'Percentage of true positive: 39.080460%'
  8. >>> f"Percentage of true positive: {perc:.2%}"
  9. 'Percentage of true positive: 39.08%'

该分类下的相关小册推荐: