jeudi 12 décembre 2019

Python - Remove substring from string element in a list?

Based on all my Googling, what I'm doing should work. Tl;dr - when I extracted some tables, it was formatted weird and some of them have 'Hide ' in the field name (there is a hide option on the table itself, probably just owing to lazy formatting that it's included in the field names).

I have the table sent to a big list, and am trying to replace the 'Hide ' with '' but it's failing. I'm not sure if having consecutive if statements on the same indent line is causing an issue. Here is a snippet of the code I've tried (there is more above and below, but this is the section that is causing errors).

my_list = ['Hide Physical Characteristics Eye Colour', 'brown', 'Hide Height', '180cm', 
'Hide Weight', '75kg']

#above the if statement, I set [val_idx] to my_list.index based on keywords in the list

if 'Hide Physical Characteristics Eye Colour' in my_list[val_idx]:
    my_list[val_idx] = 'Eye Colour'
if 'Hide ' in my_list[val_idx]:
    my_list[val_idx].replace('Hide ', '')

The reason I am not explicitly replacing the second if statement with a value (i.e. hair colour) is that there are several fields that have "hide" as the only undesirable part of the field name, rather than the longer 'Hide Physical Characteristics Eye Colour' which is the only long field name I am interested in replacing, and it just seemed more simplistic to make it more direct.

Based on what I know about python (only the basics and a bit more admittedly) this should all work. The first if statement does work, but the second one still gives the 'Hide ' in the output.

Aucun commentaire:

Enregistrer un commentaire