Reputation: 189
I have multiple strings that looks like this:
“BPBA-SG790-NGTP-W-AU-BUN-3Y”
I want to compare the string to my list and if part of the string is in the list, I want to get only the part that is found on the list as a new variable.
This is my code:
mylist = ["770", "790", "1470", "1490"]
sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”
matching = [s for s in mylist if any(xs in s for xs in sq)]
print(matching)
>>> ['770', '790', '1470', '1490']
For example this is what I want to get:
mylist = ["770", "790", "1470", "1490"]
sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”
matching = [s for s in mylist if any(xs in s for xs in sq)]
print(matching)
>>> 790
Any idea how to do this?
Upvotes: 0
Views: 1305
Reputation: 4423
[s for s in mylist if s in sq]
For those who dislike brevity:
This is a list comprehension. It evaluates to a list of strings s
in mylist
that satisfy the predicate s in sq
(i.e., s
is a substring of sq
).
Upvotes: 0
Reputation: 165
try
mylist = ["770", "790", "1470", "1490"]
sq = "BPBA-SG790-NGTP-W-AU-BUN-3Y"
b = [x for x in mylist if sq.find(x) != -1]
print b
Upvotes: 1
Reputation: 1635
Not sure I get your question, but the following should do the trick
[x for x in mylist if x in sq]
It return you with a list of those elements of the list that appears in the string
Upvotes: 1
Reputation: 36
You can use the in
keyword from python:
mylist = ["770", "790", "1470", "1490"]
sq = "BPBA-SG790-NGTP-W-AU-BUN-3Y"
for i in mylist:
if i in sq:
print(i)
The code iterates through the list and prints the list element if it is in the string
Upvotes: 2
Reputation: 27547
Like this, you can use a list comprehension:
mylist = ["770", "790", "1470", "1490"]
sq = "BPBA-SG790-NGTP-W-AU-BUN-3Y"
matching = [m for m in mylist if m in sq]
print(matching)
Output:
['790']
Upvotes: 3