Question

I have the following For loop in one line:

var = ''.join('%02x' % ord(b) for b in string_var)

How is it displayed in a regular for loop?

Was it helpful?

Solution

Using slow string concatenation:

var = ''
for b in string_var:
    var += '%02x' % ord(b)

What you have there is a generator expression; it really produces a sequence to pass to the str.join() method. ''.join() concatenates the sequence into a string with an empty delimiter.

To use the ''.join() call you could build a list first:

results = []
for b in string_var:
    results.append('%02x' % ord(b))
var = ''.join(results)

or use a generator function to do the same:

def to_hex(lst):
    for b in lst:
        yield '%02x' % ord(b)

var = ''.join(to_hex(string_var))

OTHER TIPS

This is less efficient than join, as it forces Python to allocate memory for a new string each time you do +=, but it still works

var = ''
for b in string_var:
    var += '%02x' % ord(b)

Also, you can speed up your code by turning join's argument into list:

var = ''.join(['%02x' % ord(b) for b in string_var])

Probably the easiest way to accomplish that is by using binascii.hexlify:

from binascii import hexlify 
var = hexlify('uhh'.encode())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top