Home > Blockchain >  Python if x is not None statement
Python if x is not None statement

Time:02-01

This is my code:

level = '(Something '
level = re.sub(r'[()]', '', str(level).lower()) if level is not None else None

How can I code this properly?

If I dont include the "else None" part it raises an error. I want to apply second line only if level is not None, otherwise ignore it. Is there a way of ignoring the operation in case level is None, using only 1 Python line?

CodePudding user response:

It's not possible to exclude the 'else' in a one line conditional however one workaround would be the following:

level = '(Something '
level = re.sub(r'[()]', '', str(level).lower()) if level is not None else level

CodePudding user response:

Why not just

level = '(Something '
if level is not None:
    level  = re.sub(r'[()]', '', str(level).lower())

CodePudding user response:

If I dont include the "else None" part it raises an error.

Indeed, you have used ternary operator which is ternary.

Is there a way of ignoring the operation in case level is None, using only 1 Python line?

You can use normal if without return after :, consider following simple example

x = 0
if x>0: x=10
print(x)

which output 0 as is, 10 if you change x to 1. Important: before usage consult your organization's standing coding style requirements to see if such code is compliant with them.

CodePudding user response:

What about turning it from two lines into one line, like this:

level = re.sub(r'[()]', '', str(level).lower()) if level is not None else '(Something '

I don't know how can level be None when you assign '(Something ' to it in the first line (as someone already pointed out in the comments). But if you merge those two lines into one, then there is a chance that level could be None. Hence, the logic is a little bit different than what you wrote.

CodePudding user response:

I don't know what re is, but your else statement is redundant. Try the following:

level = '(Something ' 
level  = re.sub(r"[()]", "", str(level).lower()) if not level is None

CodePudding user response:

Try this ? This is much common

level = '(Something ' # Create variable
if level is not None: # If statement
    level  = re.sub(r'[()]', '', str(level).lower()) # Execute the command needed
  •  Tags:  
  • Related