Python Strings: Medical Insurance Project

I was asked to calculate the average insurance costs for the Medical Insurance Project. I am not sure why my function doesn’t work, could someone please help? Thanks!

total_insurance_costs = 0
for record in insurance_costs:
record.remove(’$’)
total_insurance_costs += float(record)
average_insurance_costs = total_insurance_costs/len(insurance_costs)
print(average_insurance_costs)


https://www.codecademy.com/paths/data-science/tracks/dscp-python-fundamentals/modules/dscp-python-strings/projects/ds-python-strings-project

From documentation (https://docs.python.org/2/tutorial/datastructures.html):

list. remove ( x )

Remove the first item from the list whose value is x . It is an error if there is no such item.

remove() is a list method, not a string method.

1 Like

Thanks a lot! But what if “$” is in an item of a list like below.

[’$7010.0’, ‘$4050.0’, ‘$12060.0’, ‘$7500.0’, ‘$3022.0’, ‘$4620.0’, ‘$16330.0’, ‘$2900.0’, ‘$19370.0’, ‘$7045.0’]

How can I remove all the $?

I’m new to python, sorry for asking these simple questions :pray:

@yizuhi was going to suggest the replace() method. It’s also great that @lisalisaj brings up that whenever in doubt, your first go-to should be documentation :slight_smile:

>>> "pita bread".replace('pita ','')
'bread'
3 Likes

No apologies necessary. We are all learners here. :slight_smile:

Also, this might help:
https://docs.python.org/3/library/stdtypes.html#string-methods

2 Likes

Thanks all for the help :slight_smile: The problem is solved with .replace ( ) :clap: :clap: :clap:

1 Like

sorry, guys - I still didn’t manage to take away the $ sign

please help

Have you checked the earlier comments discussing this and the link to the docs?

As noted above .remove is not a string method and only works for mutable sequences. Oddly enough an attribute useful for this was added in Python 3.9 .removesuffix but the lesson will likely be running an earlier version so it won’t work. The .replace method has already been suggested, have you tried it? What was the code you used and what was the output?

Some of the .strip based methods (left/right etc.) might also be suitable, for details check the docs form the links already provided.

1 Like

found the solution:

total_cost = 0
cost = []
for i in insurance_costs:
  cost.append(i.replace('$',''))

for i in cost:
  total_cost += float(i)

avg_cost = total_cost / len(insurance_costs)

print('Average Insurance Cost :', round(avg_cost,3))
1 Like

Another option is to create a new list and then remove the $ sign :slight_smile:

insurance = []
for insure in insurance_costs:
  insurance.append(insure.strip("$"))
print(insurance)

I hope that helps!