David David - 4 years ago 1960
Python Question

AttributeError: 'float' object has no attribute 'replace'

I have got a problem with my code. I am trying to find the string

.0
to replace it with an empty string, but I got an error: AttributeError: 'float' object has no attribute 'replace'

When I try this:

program_width = program_minutes * 11.4
program_width.replace('.0', '')
print program_width


The error are jumping on this line:

program_width.replace('.0', '')


Here is the output:

23:28:36 T:3472 NOTICE: 342.0
23:28:36 T:3472 NOTICE: 342.0
23:28:36 T:3472 NOTICE: 684.0
23:28:36 T:3472 NOTICE: 684.0
23:28:36 T:3472 NOTICE: 285.0
23:28:36 T:3472 NOTICE: 114.0
23:28:36 T:3472 NOTICE: 684.0
23:28:36 T:3472 NOTICE: 684.0
23:28:36 T:3472 NOTICE: 342.0
23:28:36 T:3472 NOTICE: 2052.0


Here is what I am trying to achieve:

23:28:36 T:3472 NOTICE: 342
23:28:36 T:3472 NOTICE: 342
23:28:36 T:3472 NOTICE: 684
23:28:36 T:3472 NOTICE: 684
23:28:36 T:3472 NOTICE: 285
23:28:36 T:3472 NOTICE: 114
23:28:36 T:3472 NOTICE: 684
23:28:36 T:3472 NOTICE: 684
23:28:36 T:3472 NOTICE: 342
23:28:36 T:3472 NOTICE: 2052


Can you please help me how to fix this?

Answer Source

Well, you could convert to a string and then replace. This pretty much works by taking a number, converting a string, replacing the .0 ending, and then converting it to a number.

yourNumber = eval(str(program_width).replace('.0', ''))

You could also convert this to a function.

def removeZeroEnd(num):
    return eval(str(num).replace('.0', ''))

which can be called with

removeZeroEnd(2.0)

This is a good solution if you are handling several different numbers after the decimal. If it is only .0, use yourVar = int(yourVar).

Edit: As @PaulRooney pointed out, this will not work if the input 2.01. If this is a possible input, you can use

def removeZeroEnd(num):
      if str(num)[-2:] == ".0":
         return eval(str(num).replace('.0', ''))
      return num
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download