Reputation: 758
I am trying to compare substring from a string that I am getting from reading a .txt file and matching it with an element of the list.
String from the .txt file is as follows:
1. Blood 75.6 gm% 12-14
2. Rash 15.4 tm/m 54-89
I have a list called data which includes the words that are occuring as a first word in the string. So,
data = ['blood', 'Rash']
f = open('my.txt', r)
for x in f:
if x.find(str(data)):
# Do something
How do I match these both and then do my operations on it?
Upvotes: 0
Views: 384
Reputation: 1269
You can use the any
operator which will return true if any word in the line of f
matches any string
in data
.
f = open('my.txt', r)
for x in f:
if any(y in x for y in data):
#Do operation
or if you want to check that every line contains at least one string
in data
. You can use the all
operator which will return true if all lines contain a string
in data
:
f = open('my.txt', r)
if all(any(y in x for y in data) for x in f):
#Do operation
Upvotes: 0
Reputation: 56
with open("my.txt") as f:
for line in f:
for i in data:
if i in line:
do_operation()
Is this what you were asking for?
Upvotes: 1