How to avoid writing request.GET.get() twice in order to print it?

前端 未结 10 770
名媛妹妹
名媛妹妹 2020-12-04 21:34

I come from a PHP background and would like to know if there\'s a way to do this in Python.

In PHP you can kill 2 birds with one stone like this:

Instead of

10条回答
  •  无人及你
    2020-12-04 22:16

    Simply try:

    print(request.GET.get('q', ''))
    

    which basically prints nothing if the first argument is not present (see dict.get).


    Alternative solution would be to use a conditional expression in Python:

     if  else 
    

    but you'll end up repeating variable twice, for example:

    print(request.GET.get('q') if request.GET.get('q') else '')
    

    For variable assignments in loops, check in here.

提交回复
热议问题