How to split a string into n equal parts in python 3.8 without using functions?

Asked

Viewed 108 times

0

I want to split a string, in the case of a binary number, to convert into octal and Hex, but I need to divide the inserted number into equal parts, in the case of octal, I would need to divide it 3 by 3. how can I do this in python 3.8. Ps: without using ready functions, I believe that by for or while I would, but I’m not sure. Please help me.

n = input("Binario:")
o = ""

for i in range(len(n)-2):
  if(n[0+i]+n[1+i]+n[2+i] == "000"):
    o = o + "0"
  if(n[0+i]+n[1+i]+n[2+i] == "001"):
    o = o + "1"
  if(n[0+i]+n[1+i]+n[2+i] == "010"):
    o = o + "2"
  if(n[0+i]+n[1+i]+n[2+i] == "011"):
    o = o + "3"
  if(n[0+i]+n[1+i]+n[2+i] == "100"):
    o = o + "4"
  if(n[0+i]+n[1+i]+n[2+i] == "101"):
    o = o + "5"
  if(n[0+i]+n[1+i]+n[2+i] == "110"):
    o = o + "6"
  if(n[0+i]+n[1+i]+n[2+i] == "111"):
    o = o + "7"
print(o)

I did so, but he takes values without having to take.

  • 1

    Hello @Marcusloureiro, do not put code picture, paste the code between three single inverted quotes (código)

  • This here maybe it helps (although it is with lists, with strings you can also use what is there).

1 answer

0


Hello

Splitting string

>>> bs = '0010010010001100'

>>> n = 3
>>> while (len(bs) % n) != 0:
...     bs = '0' + bs
...

The variable n has the size of the parts where the string needs to be broken.

The while ensures that the string has the minimum size to be divisible by n (in case three). The size of bs is, in this example, equal to 16. Which is not divisible by 3, thus being a 0 is added at the beginning of string. In the second passage the size of bs is 17 and once again is added a 0 in front of bs. Finally, the size of bs is equal to 18 and the loop ends.

>>> bs
'000010010010001100'

>>> partes = [bs[index : index + n] for index in range(0, len(bs), n)]

>>> partes
['000', '010', '010', '010', '001', '100']

The variable partes receives a list from a list comprehension which would be the same as below:

partes = []
for index in range(0, len(bs), n):
    partes.append(bs[index : index + n])

The command for iterate on a range varying from 0 until 18 (based on the example, jumping from n in n, that is, of 3 in 3.

Are included in the list partes the slicing of bs. At the first moment the loop would be bs[0:0+3] - 000 - , in the second would be bs[3:3+3] - 010 - and so on.

Using the good thing about Python

>>> bs = '0010010010001100'

>>> hexs = f'{int(bs, 2):X}'
>>> hexs
'248C'

>>> octs = f'{int(bs, 2):o}'
>>> octs
'22214'

>>> f'{int(bs, 2)}'
'9356'
  • Hello. I didn’t understand the code, could you explain me? in case the while part and the parts = ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.