954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Making sense of this code snippet in python

hi friends!
i was searching for a base conversion script in python when i was stumped with the following code snippet
[code language=python]
>>> 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')
'1111101000'
[/code]

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)

krazineurons
Newbie Poster
4 posts since Jul 2008
Reputation Points: 10
Solved Threads: 0
 

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

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

3
E
8


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

1111101000

Agni
Practically a Master Poster
655 posts since Dec 2007
Reputation Points: 431
Solved Threads: 116
 

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?

krazineurons
Newbie Poster
4 posts since Jul 2008
Reputation Points: 10
Solved Threads: 0
 

Try one of the online books or tutorials. This is a link to the "Dive Into Python" chapter on string formatting http://diveintopython.org/native_data_types/formatting_strings.html

woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
 

thanks all! marking the thread as solved..

krazineurons
Newbie Poster
4 posts since Jul 2008
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You