1

A value like 0x0F or 0x05 has to be given to a function as a string without the 0x at the beginning so 0F or 05.

If I use str(hex(0x0F))[2:4] I only get f. It is crucial that the missing 0 is still present in my application.

How can i do that?

1 Answer 1

3

You'd use str.format:

In [1]: '{:02X}'.format(0x0F)
Out[1]: '0F'

In this context {:02X} is equivalent to {0:02X}. Preceding the colon with 0 tells Python to apply this to the first argument of str.format (0x0F in this example). 02 sets the minimum field width to 2 and

Preceding the width field by a zero ('0') character enables sign-aware zero-padding for numeric types

X is one of the available integer presentation types:

Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9.

Both quotes are from Format Specification Mini-Language.

Sign up to request clarification or add additional context in comments.

3 Comments

What means In[14] and Out[14]?
@Creatronik this is what IPython shell adds. You can safely ignore it.
Ok, this works fine, but can you give me a link, where this whole {:02X} statement is explained more in detail? Or maybe do it yourself right away :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.