Proper Way To Test For "x" Or "y" In A String?
Solution 1:
In Python an object x
is called truthy if bool(x) is True
, i.e. the object is equivalent to True
in a boolean context.
# alt.2 - Not working code. Will always evaluate True (Why?)if"red" or "green"in color:
That expression is evaluated as "red" or ("green" in color)
. Since "red"
is truthy, so is the expression (the second part is not even evaluated).
# alt.3 - Not working code. Will always evaluate Red True, but not Green (Why?)if ("red" or "green") in color:
The expression in parentheses evaluates to "red"
, because in Python or
and and
return their arguments. or
returns either the first argument, if it is truthy, or the second argument in any other case. So, the entire statement can be reduced to if 'red' in color: ...
Your fourth example is equivalent to the second one: those parentheses change nothing.
# alt. 5 - Working code, but I want to accept ex. 'dark green'if color in {"red", "green"}
Then nothing stops you from adding the colour to that set: {"red", "green", "dark green"}
.
What is the best way to write v1_alt.1
There are hardly any "best ways", as these things tend to be a matter of taste. That being said, if you have a fixed set of colours, I'd use a tuple or a set as in your "alt 5" example. If you have a fixed set of base colours and the modifiers are always expected to be in the beginning (as in "dark green") and space-separated, you can split incomming strings: if color.split()[-1] in base_colors
, where base_colors
is a set/tuple/list/(any searchable data structure) of base colours. If your task demands complicated logic, you'd be far better off with a dedicated function:
defvalidate_color(base_colors, color):
"""
Validate a color.
"""return color.split()[-1] in base_colors
if validate_color(base_colors, color):
...
A function encapsulates implementation details that would otherwise "pollute" your main execution graph. Moreover, it can be safely modified without ever touching the other parts (as long as you keep it pure).
Post a Comment for "Proper Way To Test For "x" Or "y" In A String?"