hi friends!
i was searching for a base conversion script in python when i was stumped with the following code snippet

>>> number = 1000
>>> hex2bin = {"0":"0000", "1":"0001", "2":"0010", "3":"0011",
            "4":"0100", "5":"0101", "6":"0110", "7":"0111",
            "8":"1000", "9":"1001", "A":"1010", "B":"1011",
            "C":"1100", "D":"1101", "E":"1110", "F":"1111"}
>>> "".join([hex2bin[h] for h in '%X'%number]).lstrip('0')

now i made my own base converter but the code above had some points i didn't understand, and i was hoping if you guys can assist me in understanding it.

1)"".join method, to which string are we calling .join??
2)[hex2bin[h] for h in '%X'%number], hex2bin is a dictionary, which is using some generator expression or string formatters or list comprehensions to generate data. how it works? where can i find more about it? what is it called?

can anyone of you please help me out with it?
thanks and regards
Anirudh (python newbie)

hex2bin[h] will give the value for the key 'h'.
i executed each statement separately, without declaring the dictionary and the output will make things very clear to you

>>for h in '%X'%number:
        print h


now you can see that 'h' gets values 3,E,8. All these values are 'key's in the dictionary hex2bin. lets see what are the values for each key

hex2bin[3] = 0011
hex2bin[E] = 1110
hex2bin[8] = 1000

0011 1110 1000

hence 'join' is joining these 3 strings and stripping(lstrip) the leading 0's hence the output


commented: good explanation +4

hi agni..! thanks for making the things clear, it was perfect.however there's one doubt still: the "%x"%number, this as i understand is using '%x' to convert number to hexadecimal and then % with number. i tried it, it works but how does it work?

number = 1000
p = '%x' % number --> how does it yield a string to p?, where can i find more about it?

thanks all! marking the thread as solved..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.