Python Strings: Medical Insurance Project

Help needed:

I have trouble deleting the whitespace in the created records. Anyone who would be able to help me? Only the last list item seems to have the whitespace deleted but not the remaining ones.

medical_data =
“”“Marina Allison ,27 , 31.1 ,
#7010.0 ;Markus Valdez , 30,
22.4, #4050.0 ;Connie Ballard ,43
, 25.3 , #12060.0 ;Darnell Weber
, 35 , 20.6 , #7500.0;
Sylvie Charles ,22, 22.1
,#3022.0 ; Vinay Padilla,24,
26.9 ,#4620.0 ;Meredith Santiago, 51 ,
29.3 ,#16330.0; Andre Mccarty,
19,22.7 , #2900.0 ;
Lorena Hodson ,65, 33.1 , #19370.0;
Isaac Vu ,34, 24.8, #7045.0"”"

Add your code here

print(medical_data)
updated_medical_data = medical_data.replace("#", “$”)
print(updated_medical_data)

print number of records

num_records = 0
for records in updated_medical_data:
if records == “$”:
num_records +=1
print(“There are” + str(num_records) + “medical records in the data.”)

splitting the data into a list of each medical record

medical_data_split = updated_medical_data.split(";")
print(medical_data_split)

Let’s split each medical record into its own list.

medical_records =
for record in medical_data_split:
medical_records.append(record.split(","))
print(medical_records)

cleaning whitespace

medical_records_clean =

outside loop that goes through each record in medical_records

for record in medical_records:

empty list that will store each cleaned record

record_clean =

nested loop to go through each item in each medical record

for item in record:
# cleaning the whitespace for each record using item.strip()
record_clean.append(item.strip())

add the cleaned medical record to the medical_records_clean list

medical_records_clean.append(record_clean)
print(medical_records_clean)

I’d have a very close look at the loops where you’re trying to strip any whitespace. If you can’t spot anything by eye then it’d be worth starting to debug a little which can be started with some well placed print statements to see what’s going on in your loops (are things doing what you expect?).

If you’re posting code to the forums could you please format it as per the guidance at- How do I format code in my posts?. A link to the project wouldn’t hurt either :slightly_smiling_face:.

2 Likes

There are two “whitespace” characters in the string. There is a space " " and a newline “\n”.

These two lines will remove both types of whitespace characters.

item = item.strip(" ")
item = item.strip("\n")

Using strip without arguments should remove both kinds of whitespace which would save you the trouble of specifying the characters or their order- https://docs.python.org/3/library/stdtypes.html#str.strip. If you view the raw original post (hit the ... then the </> button) you can catch how these loops and appends are ordered which is what @byte7345305615 needs to be looking at.

1 Like