Use the format() function with a '02x' format.
>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'
The 02 part tells format() to use at least 2 digits and to use zeros to pad it to length, x means lower-case hexadecimal.
The Format Specification Mini Language also gives you X for uppercase hex output, and you can prefix the field width with # to include a 0x or 0X prefix (depending on wether you used x or X as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:
>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
Answer from Martijn Pieters on Stack OverflowUse the format() function with a '02x' format.
>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'
The 02 part tells format() to use at least 2 digits and to use zeros to pad it to length, x means lower-case hexadecimal.
The Format Specification Mini Language also gives you X for uppercase hex output, and you can prefix the field width with # to include a 0x or 0X prefix (depending on wether you used x or X as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:
>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
I think this is what you want:
>>> def twoDigitHex( number ):
... return '%02x' % number
...
>>> twoDigitHex( 2 )
'02'
>>> twoDigitHex( 255 )
'ff'
import colorsys
import time
def drawRainbow():
with open("/sys/devices/platform/system76/leds/system76::kbd_backlight/color_left", "r+") as f:
for i in range(1000):
r, g, b = colorsys.hsv_to_rgb(i/100, 1.0, 1.0)
hexcolor = '%02x%02x%02x' % (int(r*255), int(g*255), int(b*255))
f.write(hexcolor)
f.flush()
time.sleep(2)
while True:
drawRainbow()I'm trying to read through the code, but I'm not quite sure what to make of those two parts. Could someone explain? The '%' I know is a modulus operator, but I don't quite understand how to apply that to the particular line of code.
Hello all,
I am having trouble understanding what this statement does. This statement is supposed to help me format mac addresses as they are received, but I don't see why we would need to format mac addresses to two decimal places when mac addresses don't have decimals. Am I missing something?
You can use string formatting for this purpose:
>>> "0x{:02x}".format(13)
'0x0d'
>>> "0x{:02x}".format(131)
'0x83'
Edit: Your code suggests that you are trying to convert a string to a hexstring representation. There is a much easier way to do this (Python2.x):
>>> "abcd".encode("hex")
'61626364'
An alternative (that also works in Python 3.x) is the function binascii.hexlify().
You can use the format function:
>>> format(10, '02x')
'0a'
You won't need to remove the 0x part with that (like you did with the [2:])