0

Im trying to do a simple check if there is 3 specific value in a string. If there is, the statement should return nothing, instead of save.

Here is my code, but I think the syntax is wrong:

if not ('2239687' or '2238484' or '2239440') in user_id:
    #The user is not admin, save the user
    web_user.save() 

To elaborate, I want it to test if user_id is "2239687" or "2238484" or "2239440" (and not, for example, "002239440"). If the user_id is one of those three values (and ONLY those three values), the statement should return false.

6
  • If you wanna see what's happening: diveintopython.net/power_of_introspection/and_or.html Commented Mar 26, 2013 at 8:40
  • To clarify, 1) "user_id" is a string, right? 2) should it return True if user_id = 99922396879999? Commented Mar 26, 2013 at 9:07
  • Yes user_id should be a string. All other values should return True, but these three values should return False. Is there some way I can test if the user_id is a string or not? Commented Mar 26, 2013 at 9:20
  • @Garreth00: now I'm confused. Are you testing if user_id contains "2239687" (or 2238484 or 2239440) - as in "99922396879999" - or if it's equal to "2239687" (or 2238484 or 2239440)? Commented Mar 26, 2013 at 9:24
  • @thg435: I want it to test if user_id is "2239687" or "2238484" or "2239440" (and not "002239440") If the user_id is one of those three values (and ONLY those three values), the statement should return false Commented Mar 26, 2013 at 9:33

3 Answers 3

2
if not any(x in user_id for x in ('2239687', '2238484', '2239440')):
    #The user is not admin, save the user
    web_user.save() 

This checks whether none of the three string is present within user_id.

Sign up to request clarification or add additional context in comments.

Comments

2

One more option:

if not any(idx in user_id for idx in ('2239687' ,'2238484' , '2239440')):
    # do something

4 Comments

This should not be used in this case
@jamylak yes, maybe you are right, then just a case to know that 'any' function exists
@glglgl i know - but each ohe us can only suppose what type of comparison he need - the option here is 'any' function not a comparison type
id is a built-in function. Don't use it as a variable name.
1

Try like this

if user_id not in ('2239687' ,'2238484' , '2239440'):

Or

if not user_id in ('2239687' ,'2238484' , '2239440'):

3 Comments

This seems right, but the "save" does still gets executed me (I'm 2239687).
@Garreth00 str(2239687) not in ('2239687' ,'2238484' , '2239440') try like this,
Correct me but i always thought that 'not user_id in ('2239687' ,'2238484' , '2239440'):' is not very pythonic?

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.