Jul-12-2020, 03:07 AM
In this specific case I don't see any downside to just doing the split initially. You can find out if the '=' is present from the result of the split.
If split behaved differently than it does and failed when the split character was not present, then I'd probably wrap it in a try/except. I'm not sure if that's useful, or if I've misinterpreted something.
l = ["no equals", "this=that"] for s in l: items = s.split('=', maxsplit=1) if len(items) > 1: # has the equals print(f"{items[0]} -> {items[1]}") else: print(f"'{items[0]}' didn't have an equals sign")And if you wanted to, you could use the walrus operator to combine the split and the if lines.
If split behaved differently than it does and failed when the split character was not present, then I'd probably wrap it in a try/except. I'm not sure if that's useful, or if I've misinterpreted something.