0

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?

5 Answers 5

3

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']
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

That was exactly what I wanted. Thank you
1

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

Comments

1

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

1 Comment

While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation.
0

[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).

1 Comment

Code-only answer values nothing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.