1

I have a problem.
I have an product.address like this 'UK some city some road'

And I want to compare this address,if it is start with UK or US or AS or GE
I will save product.dstore_id = 2,otherwise, save product.dstore_id = 1

My code is like this:

area = [UK,US,AS,GE]
for i in area:
    if i in product.address:
        product.dstore_id = 2
    else:
        product.dstore_id = 1

But I found this has a big problem,it will compare all the i and save the wrong number
So how can I do to reach it . Please guide me a bit Thank you

1 Answer 1

4

You could use any. This will return True if any of the items in your area list are present in the product.address. You then no longer need the for loop.

if any(address.startswith(i) for i in area):
    product.dstore_id = 2
else:
    product.dstore_id = 1

For example

area = ['UK','US','AS','GE']
address =  'UK some city some road'
>>> any(addres.startswith(i) for i in area)
True
Sign up to request clarification or add additional context in comments.

1 Comment

startswith is safer & more efficient, eg product.dstore_id = 2 if any(address.startswith(i) for i in area) else 1

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.