Python inline elif possible?

前端 未结 7 2247
耶瑟儿~
耶瑟儿~ 2021-02-07 11:16
\'Hello \' + (\'there\' if name is None else name)

Is the equivalent of

msg = \'Hello \'
if name is None:
    msg += \'there\'
else:
          


        
7条回答
  •  滥情空心
    2021-02-07 12:13

    You could also do this:

    msg= 'Hello ' + {name is None: 'there', name == 'Mr Anderson': 'Neo'}.get(True, name)
    

    So either of name is None or name == 'Mr Anderson' is True, or none of them is True, then name will be used.

提交回复
热议问题