mardi 19 novembre 2019

Python elif not working as expected for string find

I would like to pull out the locations for an inconsistently formatted data field in a Pandas dataframe. (I do not maintain the data so I cannot alter how this field is formatted.)

Running the following toy version

string2 = 'Denver.John'
if string2.find(' -'):
    string2 = string2.split(' -')[0]
elif string2.find('.'):
    string2 = string2.split('.')[0]
print(string2)

gives me Denver.John instead of Denver. However, if I use an if instead:

string2 = 'Denver.John'
if string2.find(' -'):
    string2 = string2.split(' -')[0]
if string2.find('.'):
    string2 = string2.split('.')[0]
print(string2)

I get Denver, as desired. The problem is I also have strings like 'Las.Vegas - Rudy' and I want to be able to pull out Las.Vegas in those instances so I only want to split on a period if the field does not contain the hyphen (' - ').

Why does the elif not work for Denver.John?

Aucun commentaire:

Enregistrer un commentaire