替换字符串

时间:2014-09-08 19:58:58

标签: python

我正在使用我的python脚本在变量program_top中添加数字。

我有返回字符串315.0,我想将其替换为315

当我使用它时:

program_top = 315 + 37.5 * idx

结果如下:

20:48:02 T:3876  NOTICE: 315.0
20:48:02 T:3876  NOTICE: 315.0
20:48:02 T:3876  NOTICE: 315.0
20:48:02 T:3876  NOTICE: 315.0
20:48:02 T:3876  NOTICE: 315.0
20:48:02 T:3876  NOTICE: 315.0
20:48:02 T:3876  NOTICE: 315.0
20:48:02 T:3876  NOTICE: 315.0
20:48:02 T:3876  NOTICE: 315.0
20:48:02 T:3876  NOTICE: 315.0
20:48:02 T:3876  NOTICE: 315.0

我想得到这样的结果:

20:48:02 T:3876  NOTICE: 315
20:48:02 T:3876  NOTICE: 315
20:48:02 T:3876  NOTICE: 315
20:48:02 T:3876  NOTICE: 315
20:48:02 T:3876  NOTICE: 315
20:48:02 T:3876  NOTICE: 315
20:48:02 T:3876  NOTICE: 315
20:48:02 T:3876  NOTICE: 315
20:48:02 T:3876  NOTICE: 315
20:48:02 T:3876  NOTICE: 315
20:48:02 T:3876  NOTICE: 315

您能否告诉我如何使用program_top = 315 + 37.5 * idx删除.0以用空字符串替换它?

1 个答案:

答案 0 :(得分:3)

使用program_top = int(315 + 37.5 * idx)。这会将float转换为整数,因此不会有小数位。如果您只想删除以.0结尾的小数位,请尝试:

program_top = 315 + 37.5 * idx
if not program_top % 1.0:
    program_top = int(program_top)

字符串方法:

program_top = str(315 + 37.5 * idx)
program_top = program_top[:-2] if program_top.endswith(".0") else program_top

但是,基于数字的解决方案(上面)更好。