Search code examples
pythonif-statementeval

Using ':' for all range in an IF statement - Python


I am wondering how I can use the ':' symbol in an IF statement. For example - if a condition is true, I want to use all values; else use only some values.

The code is-

If condition_true:
   data['column1'][:]
else:
   data['column1'][x:y]

I am wondering if I can use something like this-

If condition_true:
   var = ':'
else:
   var = 'x:y'
data['column1'][eval(var)]

But obviously this is not working with the eval function.

How can I achieve this?

Thank you


Solution

  • You may want to wrap the whole last statement and use .format(...) to inject your variable into the string.

    If condition_true:
       var = ':'
    else:
       var = 'x:y'
    eval("data['column1'][{}]".format(var))