uq3*_*rbm 1 python string conditional-statements
I have a variable, p, that is the output of a regular expression match and is guaranteed to be either 'true' or 'false' in any mixed case. If 'true' I want it to be 'FALSE' and if 'false' I want it to be 'TRUE'. The end result is always uppercase.
I have thought of the following four methods. Which is the most pythonic or is there a better one?
p=['TRUE','FALSE'][eval(p.capitalize())]
p=(not eval(p.capitalize())).__repr__().upper()
p='FALSE' if eval(p.capitalize()) else 'TRUE'
p={'TRUE':'FALSE','FALSE':'TRUE'}[p.upper()]
Run Code Online (Sandbox Code Playgroud)
IMO, the most pythonic way isn't with eval, or with dunders, or using a 2-element list indexing, it's a simple if-else conditional (or ternary):
p = 'TRUE' if p.upper() == 'FALSE' else 'FALSE'
Run Code Online (Sandbox Code Playgroud)
It doesn't use hacks or trickery, it is simple and (more importantly) readable.
| 归档时间: |
|
| 查看次数: |
56 次 |
| 最近记录: |