Search code examples
pythonhex

What is the CORRECT way to separate color HEX values from each other?


I made a small Python program that renders an image by drawing pixels with a predefined color (in HEX values, which is important).

Input

I made a test HEX string that lists all blue values (it looks something like this: "000000000001000002000003000004...")

But when I insert this line into my program, the color values jump around for some reason.

Expected

it should be something like this:

  • (color picker #000000, brush down, 1 step, brush up),
  • (color picker #000001, brush down, 1 step, brush up),
  • (color picker #000002, brush down, 1 step, brush up), etc.

Actuel output

But in the program, for some reason, it is redone like this:

  • (color picker #000000, brush down, 1 step, brush up),
  • (color picker #000010, brush down, 1 step, brush up),
  • (color picker #000200, brush down, 1 step, brush up),
  • (color picker #003000, brush down, 1 step, brush up),
  • (color picker #040000, brush down, 1 step, brush up)
  • etc.

Can this be fixed so that the program works properly?

Full program code:

import turtle as tur

hexString = input('Введите HEX-строку БЕЗ пробелов: ')

tur.clear()
tur.penup()

startX = -380
startY = 320

tur.goto(startX, startY)

a = 0
hexColors = []
hexColorTemp = ''

for hexColorPart in hexString:
    a += 1

    if a < 7:
        hexColorTemp += hexColorPart
    elif a == 7:
        a = 0
        hexColors.append(hexColorTemp)
        hexColorTemp = ''

for fullColor in hexColors:
    if tur.xcor() < 370:
        print(tur.pos())
        print(fullColor)
        print()
        tur.pencolor('#' + fullColor)
        tur.pendown()
        tur.fd(1)
        tur.penup()
    elif tur.xcor() == 370:
        startY -= 1
        tur.goto(startX, startY)
        print(tur.pos())
        print(fullColor)
        print()
        tur.pencolor('#' + fullColor)
        tur.pendown()
        tur.fd(1)
        tur.penup()

tur.mainloop()

P.S. In the debugging program, the display of the current color and the position of the brush is enabled.

I tried to write 6 instead of 7, in 20 and 22 lines of code, but it didn't help.


Solution

  • The issue is that when you reach a==7 you don't do hexColorTemp += hexColorPart so you miss the current hexColorPart

    You always need to append hexColorPart, then if the length is 6, save it and clear hexColorTemp

    hexColors = []
    hexColorTemp = ''
    for hexColorPart in hexString:
        hexColorTemp += hexColorPart
        if len(hexColorTemp) == 6:
            hexColors.append(hexColorTemp)
            hexColorTemp = ''
    

    But the nicest way to get based-length groups is to slice like

    hexColors = [hexString[i:i + 6] for i in range(0, len(hexString), 6)]