Python: try statement in a single line

前端 未结 13 1608
囚心锁ツ
囚心锁ツ 2020-12-01 03:47

Is there a way in python to turn a try/except into a single line?

something like...

b = \'some variable\'
a = c | b #try statement goes here
<         


        
相关标签:
13条回答
  • 2020-12-01 04:51

    Works on Python3, inspired by Walter Mundt

    exec("try:some_problematic_thing()\nexcept:pass")
    

    For mulitiples lines into one line

    exec("try:\n\tprint('FirstLineOk')\n\tsome_problematic_thing()\n\tprint('ThirdLineNotTriggerd')\nexcept:pass")
    

    Ps: Exec is unsafe to use on data you don't have control over.

    0 讨论(0)
提交回复
热议问题