-1

I am pretty new to python syntax ... how do I use the or operator in this scenario?

To check if files end with either '.txt' or '.sm3dump', I tried to use any(), but I got a SyntaxError:

if any(filename.endswith('.txt'), filename.endswith('.sm3dump'))
                                                               ^
SyntaxError: invalid syntax

What did I do wrong?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
Eric T
  • 1,026
  • 3
  • 20
  • 42
  • 5
    For or operator simply type `or`. And put a `:` at the end of your `if`. `if filename.endswith('.txt') or filename.endswith('.sm3dump'):` you can find this quickly using google though... – swenzel Mar 24 '15 at 07:49

1 Answers1

4

You've called any() with two arguments:

any(filename.endswith('.txt'), filename.endswith('.sm3dump'))
#   <----- argument #1 ----->  <------- argument #2 ------->

... but it only takes one, which must be an iterable (a list, tuple, etc.):

any([filename.endswith('.txt'), filename.endswith('.sm3dump')])
#   <-------------- one list with two elements -------------->

If you wanted to use or instead, it's straightforward:

filename.endswith('.txt') or filename.endswith('.sm3dump')

A common idiom when using any() to perform multiple similar tests is to use a list comprehension or generator expression:

any([filename.endswith(ext) for ext in ('.txt', '.sm3dump')])
#   <----------------- list comprehension ----------------->
any(filename.endswith(ext) for ext in ('.txt', '.sm3dump'))
#   <-------- generator expression (no brackets) -------->

Although in this case, you can actually supply a tuple of strings to str.endswith(), and it'll check them all:

filename.endswith(('.txt', '.sm3dump'))

Whichever test you use, you need to remember to end your if statement with a colon:

if filename.endswith(('.txt', '.sm3dump')):
    # do something ...
Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • 1
    Eric: To discover things like the last part of Zero's answer, use `help` at an interactive prompt to quickly check the signature and use of functions and classes. In particular, `>>> help(str.endswith)` ends with " suffix can also be a tuple of strings to try". – Terry Jan Reedy Mar 24 '15 at 22:51