samedi 13 mars 2021

Using logical operators instead of control flow?

I will keep this short. I was reviewing code for Hex Filter (To filter out non-character ASCII values)

code:

HEX_FILTER = ''.join([(len(repr(chr(i))) == 3) and chr(i) or '.' for i in range(256)])

Output:

................................ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[.]^_`abcdefghijklmnopqrstuvwxyz{|}~..................................¡¢£¤¥¦§¨©ª«¬.®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ

I was confused on what's going on, so I wrote my approach to get above output. My code is as follows:

HEX_FILTER = ''.join(['.' if (len(repr(chr(i))) != 3) else chr(i) for i in range(256)])

The idea is repr of non-alphabet will be more than 3. If it's not 3 use '.' else use the character.

I cannot wrap my mind around on as to, How len(repr(chr(i))) == 3) and chr(i) or '.' equates to '.' if (len(repr(chr(i))) != 3) else chr(i)

Aucun commentaire:

Enregistrer un commentaire