一、python2.x
将 0.1234 转化为 12.34% 的形式:
rate = .1234
print('%.2f%%' % (rate * 100))
第一个百分号和 .2f 相连,表示浮点数类型保留小数点后两位格式化输出;
然后的两个连续的%%,则最终会输出一个%号出来,有对%进行转义的含义;
将小数(数值)转化为字符串,并赋给其他变量:
rate = .1
res = format(res, '.0%')
File "export_ad_cpm_by_day.py", line 116, in
differecedata = mergeDataframe.query("cpm_y !=0 andcpm_t >= cpm_y*1.5").assign(rate = lambda x:'{:.2%}'.format((x['cpm_t']-x['cpm_y'])/x['cpm_y'])).rename(columns={"cpm_y":"ycpm","cpm_t":"tcpm"})
ValueError: Unknown format code '%' for object of type 'str'
二、python3.x
方式1:直接使用参数格式化:{:.2%},显示小数点后2位
>>> print('percent: {:.2%}'.format(42/50)