Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python elif在字符串查找中未按预期工作_Python_If Statement - Fatal编程技术网

Python elif在字符串查找中未按预期工作

Python elif在字符串查找中未按预期工作,python,if-statement,Python,If Statement,我想为熊猫数据帧中格式不一致的数据字段提取位置。(我不维护数据,因此无法更改此字段的格式。) 运行以下玩具版本 string2 = 'Denver.John' if string2.find(' -'): string2 = string2.split(' -')[0] elif string2.find('.'): string2 = string2.split('.')[0] print(string2) 给我丹佛,约翰代替丹佛。但是,如果我改用if: string2 =

我想为熊猫数据帧中格式不一致的数据字段提取位置。(我不维护数据,因此无法更改此字段的格式。)

运行以下玩具版本

string2 = 'Denver.John'
if string2.find(' -'):
    string2 = string2.split(' -')[0]
elif string2.find('.'):
    string2 = string2.split('.')[0]
print(string2)
给我丹佛,约翰代替丹佛。但是,如果我改用if:

string2 = 'Denver.John'
if string2.find(' -'):
    string2 = string2.split(' -')[0]
if string2.find('.'):
    string2 = string2.split('.')[0]
print(string2)
我想去丹佛。问题是我也有类似“Las.Vegas-Rudy”的字符串,我希望能够在这些情况下拉出Las.Vegas,因此我只希望在字段不包含连字符(“-”)的情况下在句点上拆分


为什么elif不适用于Denver.John?

因为
find
会生成索引或
-1
,而
-1
是有效的!!!,因此,请尝试使用:

string2 = 'Denver.John'
if string2.find(' -') + 1:
    string2 = string2.split(' -')[0]
elif string2.find('.') + 1:
    string2 = string2.split('.')[0]
print(string2)
或者更像:

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

如果string2中的“-”
相反。find方法返回int

find()
如果在给定字符串中找到子字符串,则返回该子字符串的最低索引。如果没有找到,则返回-1

因此,在你的情况下:

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)

因此,在
if
语句中,可以将
find
的结果与
-1
字符串进行比较。find返回子字符串的位置,如果没有找到子字符串,则返回-1

因此,请执行以下操作:

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

谢谢我不知道,这解决了问题。是的,我会的,我不能再等10分钟