Python's equivalent to null-conditional operator introduced in C# 6

后端 未结 4 2033
时光说笑
时光说笑 2021-01-01 16:04

Is there an equivalent in Python to C# null-conditional operator?

System.Text.StringBuilder sb = null;
string s = sb?.ToString(); // No error
4条回答
  •  清酒与你
    2021-01-01 16:58

    How about:

    s = sb and sb.ToString()
    

    The short circuited Boolean stops if sb is Falsy, else returns the next expression.

    Btw, if getting None is important...

    sb = ""
    
    #we wont proceed to sb.toString, but the OR will return None here...
    s = (sb or None) and sb.toString()
    
    print s, type(s)
    

    output:

    None 
    

提交回复
热议问题