[Python] Why my function that converts a string of digits to a list of bytes doesn't work?

Discussão em 'Python' iniciado por Stack, Março 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have written a simple function that converts a string consisting of only digits ('0123456789') to a list of bytes. More specifically it finds the longest possible sequences of digits that when converted to an integer is less than 256.

    For example, given the decimal digits in order, the output should be (0, 123, 45, 67, 89).

    Now I wrote this function very quickly:

    from typing import List


    DIGITS = {str(i): i for i in range(10)}

    def get_bytes(s: str) -> List[int]:
    byte_list = []
    chunk = 0
    for c in f'{s}0':
    if (d := DIGITS.get(c)) is None:
    raise ValueError(f"{c} is not a digit")

    if (new := chunk * 10 + d) < 256:
    chunk = new
    else:
    byte_list.append(chunk)
    chunk = d

    return byte_list[not byte_list[0]:]


    In [143]: get_bytes('0000')
    ---------------------------------------------------------------------------
    IndexError Traceback (most recent call last)
    Cell In[143], line 1
    ----> 1 get_bytes('0000')

    Cell In[142], line 14, in get_bytes(s)
    11 byte_list.append(chunk)
    12 chunk = d
    ---> 14 return byte_list[not byte_list[0]:]

    IndexError: list index out of range

    In [144]: get_bytes('100100100')
    Out[144]: [100, 100, 100]

    In [145]: get_bytes('12301230123')
    Out[145]: [123, 123, 123]


    I tried to fix the code, I couldn't. Now there is only one problem remaining, and the exact problem I tried to address with this question.

    In the first example, expected output is [0, 0, 0, 0], in the third example the correct output should be [123, 0, 123, 0, 123]. How to fix this?

    And for 0, I want every isolated 0 to be one number in the output. In short I want to make sure ''.join(str(i) for i in output) == original.

    Continue reading...

Compartilhe esta Página