result = []
reader = ['sdsd-sdds', 'asaad', 'deded - wdswd', '123' ]
str_1 = 'deded -'
for row in reader:
if row.index(str_1) in row:
result.extend(row.index(str_1) + 1)
print(result)
how to find the index by its part, the program should print ['123']
The statement row.index(str1)
does not give you the index of row
in reader
; it gives you the index of str1
in row
, and this is useless for what you're trying to do, which is to get the next item after row in reader
once you've found a match (and it doesn't matter where within the string the match is found AFAICT).
You could do this by doing reader.index(row)
but it'd be easier to just enumerate reader
so that you already have the index available. Using index
is not necessarily at all since you can also just do str_1 in row
:
for i, row in enumerate(reader):
if str_1 in row:
result.append(reader[i+1])
I'd do it this way:
result = []
reader = ['sdsd-sdds', 'asaad', 'deded - wdswd', '123' ]
str_1 = 'deded -'
for x in reader:
if str_1 in x:
result.append(reader[reader.index(x) + 1])
print(result)
If you want to stop after finding the first one you should use a break after finding a value:
result = []
reader = ['deded - wdswd', 'asaad', 'deded - wdswd', '123' ]
str_1 = 'deded -'
for x in reader:
if str_1 in x:
result.append(reader[reader.index(x) + 1])
break
print(result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.