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.)
Solution 1:
Because find
either yields the index or -1
while -1
is valid!!!, so try using:
string2 = 'Denver.John'if string2.find(' -') + 1:
string2 = string2.split(' -')[0]
elif string2.find('.') + 1:
string2 = string2.split('.')[0]
print(string2)
Or better like:
string2 = 'Denver.John'if' -' in string2:
string2 = string2.split(' -')[0]
elif '.' in string2:
string2 = string2.split('.')[0]
print(string2)
Solution 2:
Solution 3:
find()
returns the lowest index of the substring if it is found in given string. If it’s not found then it returns -1.
So in your case:
string2 = 'Denver.John'print(string2.find(' -')) # prints -1print(string2.find('.')) # prints 6if string2.find(' -'):
string2 = string2.split(' -')[0]
elif string2.find('.'):
string2 = string2.split('.')[0]
print(string2)
So in your if
statement you can compare the result of find
with -1
.
Solution 4:
string.find returns a position of the substring, and it is -1 if it doesn't find the substring.
Thus, do the following instead:
string2 = 'Denver.John'if string2.find(' -') >= 0:
string2 = string2.split(' -')[0]
elif string2.find('.') >= 0:
string2 = string2.split('.')[0]
print(string2)
Post a Comment for "Python Elif Not Working As Expected For String Find"