Home > Back-end >  How the following python string are generated?
How the following python string are generated?

Time:09-01

I am reading this wsgi document, I can not understand how the response_body is generated.

    {
        response_body = html % { # Fill the above html template in
        'checked-software': ('', 'checked')['software' in hobbies],
        'checked-tunning': ('', 'checked')['tunning' in hobbies],
        'age': age or 'Empty',
        'hobbies': ', '.join(hobbies or ['No Hobbies?'])
    }

Can anyone explains the python syntax: 'checked-software': ('', 'checked')['software' in hobbies],

CodePudding user response:

Break it down:

{
    'checked-software': ('', 'checked')['software' in hobbies]
}
* 'checked-software': (...) 
    - assign the key 'checked-software' to the thing on the right-hand side
* ('', 'checked') 
    - a 2-tuple with '' and 'checked' as elements
* 'software' in hobbies' 
    - a True/False check if the string 'software' is in the hobbies variable
* ['software' in hobbies] 
    - a sequence-accessor based on the True/False check

Taking all that

'checked-software': ('', 'checked')['software' in hobbies] 

Would mean:

  • check if the string 'software' is in the hobbies variable, this becomes True or False
    • If False, access the 0th element of ('', 'checked')
    • If True, access the 1st element of ('', 'checked')
  • Assign that element to the 'checked-software' key

This is using the fact that True/False are respectively 1 and 0 in Python, because bools are integral types.

Booleans (bool)

These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of the integer type, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

CodePudding user response:

The slice at the end is a boolean, which is being used to reference the elements of the tuple. This example might help;

dictionary = {'key': ('if false', 'if true')[True]}
print(dictionary)

'software' in hobbies will return either True(1) or False(0) for example.

  • Related