0

I have a line array that values in position 5 can be either of these values:

"Tablespace Free Space (MB)", "Tablespace Space Used (%)"

if line[5] is any of these I need to do some extra work.

I have tried this:

if (line[5] in ("Tablespace Space Used (%)")|("Tablespace Free Space (MB)"))

    # some other code here

I keep getting this error:

    if (line[5] in ("Tablespace Space Used (%)"|"Tablespace Free Space (MB)"))
                                                                             ^
SyntaxError: invalid syntax
3
  • 1
    You are missing a : at the end of your line. Commented Feb 11, 2015 at 21:08
  • 1
    You need to add a ':' at the end of your if statement. For example: if (line[5] in ("Tablespace Space Used (%)", "Tablespace Free Space (MB)"): Commented Feb 11, 2015 at 21:08
  • Also, relational OR in python is "or", not pipe. Commented Feb 11, 2015 at 21:19

2 Answers 2

3

You were missing the : at the end of your if statement.

However, you are using invalid syntax for your test too; it'll lead to a runtime error (TypeError: unsupported operand type(s) for |: 'str' and 'str'). You want to create a tuple, or a set of strings to test against, not use |:

if line[5] in ("Tablespace Space Used (%)", "Tablespace Free Space (MB)"):

or

if line[5] in {"Tablespace Space Used (%)", "Tablespace Free Space (MB)"}:

The latter is technically more efficient, except if you are using Python 2 where the set isn't optimised into a constant the way the tuple would be in either version of the language. Using {...} to create a set requires Python 2.7 or newer.

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

2 Comments

@martinPeiters, I get this error: if line[5] in {"Tablespace Space Used (%)","Tablespace Free Space (MB)"}: ^ SyntaxError: invalid syntax
@user1471980: What version of Python are you using? {...} for sets requires Python 2.7 or up.
1

You use == to check equality

4 == 2*2
True

To use an if statement, conclude the line with a ':'

if line[5] in {'Tablespace Space Used (%)', 'Tablespace Free Space (MB)'}:
   do x

7 Comments

why are you using in still instead of ==?
didn't see the OP's statement 'if line[5] is any of these I need to do some extra work.' will amend.
Sure, but why not use a membership test still?
Could you elucidate? My understanding is that '==' is a membership test. docs.python.org/2/reference/…
No, == tests for equality. in tests for membership. As in something in ('valueA', 'valueB) (which is implemented by testing for equality against each element in turn) or `something in {'valueA', 'valueB'} (which uses a hash table and equality testing for a more efficient membership test).
|

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.