简体   繁体   English

Python elif 无法按预期进行字符串查找

[英]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.我想提取 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.给我 Denver.John 而不是丹佛。 However, if I use an if instead:但是,如果我使用 if 代替:

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 (' - ').问题是我也有像 'Las.Vegas - Rudy' 这样的字符串,我希望能够在这些情况下提取 Las.Vegas,所以我只想在字段不包含连字符 (' - ')。

Why does the elif not work for Denver.John?为什么 elif 对 Denver.John 不起作用?

Because find either yields the index or -1 while -1 is valid,:!, so try using:因为find要么产生索引,要么产生-1-1有效,:!,所以尝试使用:

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)

Use利用

if ' -' in string2

instead.反而。 The find method returns an int find 方法返回一个 int

find() returns the lowest index of the substring if it is found in given string.如果在给定的字符串中找到 substring,则find()返回其最低索引。 If it's not found then it returns -1.如果未找到,则返回-1。

So in your case:所以在你的情况下:

string2 = 'Denver.John'
print(string2.find(' -')) # prints -1
print(string2.find('.')) # prints 6
if 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 .因此,在您的if语句中,您可以将find的结果与-1进行比较。

string.find returns a position of the substring, and it is -1 if it doesn't find the substring. string.find 返回 substring 的 position,如果没有找到 substring,则返回 -1。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM