0

I have a set of paths I'd like to check before append it to a list. Is there a functional way to write this such that the conditional statement is less redundant?

if not path.endswith(".json") or not path.endswith(".toc") or not path.endswith("_index") or not path.endswith(...) or ...:
    some_list.append(path)
jchi2241
  • 2,032
  • 1
  • 25
  • 49
  • 5
    [`str.endswith` method](https://docs.python.org/3/library/stdtypes.html#str.endswith) also accepts a `tuple` of suffices, so you can do `path.endswith(('.toc', '_index', ...)` – Azat Ibrakov Sep 16 '19 at 06:40
  • 1
    Also, with `not` having higher priority than `or`, all this test is checking is that the string does not end with `.json`. I wonder if `not path.endswith(suffixes)` was the intended function. – Yann Vernier Sep 16 '19 at 06:50

3 Answers3

4

Python's str.endswith supports a tuple of different endings:

if not path.endswith(".json") or path.endswith((".toc", "_index", ...)):
Francis Colas
  • 3,459
  • 2
  • 26
  • 31
eumiro
  • 207,213
  • 34
  • 299
  • 261
1

You could use any() to iterate over a list of possible options

accepted = [".toc", "_index"] 
if not path.endswith(".json") or any(path.endswith(x) for x in accepted):
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
0

Maybe something like this:

file_exts = ['.json', '.toc', '_index']

if not any(path.endswith(ext) for ext in file_exts)):
    some_list.append(path)
Jethro Cao
  • 968
  • 1
  • 9
  • 19
  • This isn't the same logic. The `not` isn't applied over every element in the question – OneCricketeer Sep 16 '19 at 06:41
  • 1
    While that is true, the question's condition is probably not what was intended, as the first test renders the rest moot. – Yann Vernier Sep 16 '19 at 06:51
  • @cricket_007 Ya, realized I misread the question afterwards. Though based on the OP's title wording, I think it was implied he wanted to check for negation on all endings. – Jethro Cao Sep 16 '19 at 07:01