-1

I am trying to read in a file only if several conditions are met. However, the only method I can get working is repetative. Is there a way to simplyfy the conditions into a list and call the list, or a more simplified way of achieving this result? For example

if '$' not in file and '~' not in file and 'diab' not in file:

where file is the file name and it cannot contain the characters $,~ nor any elaboration of the word diab such as diablo.

Thank you in advance

2 Answers2

2

Use all:

symbols = ["$", "~", "diab"]
if all(symbol not in file for symbol in symbols):
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • 1
    or `not any(symbol in file for ...)`. Depending on context, might be a tad more readable (arguably, of course, but might be worth to show this alternative as well) – DeepSpace Jul 21 '22 at 10:47
0

You can put a not just at the beginning and close everything with parenthesis. Like this. \

if not('$' in file and '~' in file and 'diab' in file):

Otherwise you can substitute and with & and not with ~

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
  • 1
    How is this less repetitive? – DeepSpace Jul 21 '22 at 10:48
  • And no, you can't "substitute `and` with `&` and `not` with `~`". They don't do the same thing – DeepSpace Jul 21 '22 at 10:49
  • You avoid using two more nots. But of course the answer above is quite nice too. And of course you can, Python has byte-wise boolean operators since it's interpreter written in C. It should work. –  Jul 21 '22 at 10:50
  • You reduce the amount of characters in the line, yes, but you didn't solve the repetitiveness problem. What if other symbols are to be excluded as well? You have to add a `and symb in file` for each one, instead of just adding them to a list – Tomerikoo Jul 21 '22 at 10:52
  • Are the outputs of `print(1 and 3)` and `print(1 & 3)` the same? "It should work" is not good enough, don't suggest answers you are not sure of. – DeepSpace Jul 21 '22 at 10:53
  • This is not the equivalent of what the OP wants. Check it on `file = '~'` for example. – Guy Jul 21 '22 at 10:54
  • Ok dude, my bad, sorry. –  Jul 21 '22 at 10:54