Break string every 4 positions - Python

Asked

Viewed 131 times

1

Whereas we have the following string.

codigo = '7777. 5698 897897. 236'

After removal of spaces and .

codigo_formatado = ''.join(codigo_de_barras.split()).replace(".", "")
codigo_formatado

Exit

'77775698897897236'

How do I break the string '77775698897897236' considering the count of 4 in 4 positions so that the output is similar below:

7777
5698
8978
9723
6

3 answers

7


I think a simple tie for is simple and effective enough, no?

codigo = '77775698897897236'

for i in range(0, len(codigo), 4):
    print(str[i:i+4])

If you need the answer on a list, just make the append.

  • Your suggestion is making a mistake

  • 1

    I used a comma to separate the indexes, it should be two points.

  • 1

    I edited the answer just because the variable str was overwriting the native python string and the spaces in the Slice to comply with PEP8. ;)

4

In the session "recipes" module itertools has a function called grouper who picks up a sequence and iterates "to pieces":

from itertools import zip_longest


def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)


teste = "77775698897897236"

for grupo in grouper(teste, 4, ''):
    print("".join(grupo))

Code running on Repl.it

Upshot:

7777
5698
8978
9723
6

Edit

To answer that uses slicing is perfectly suitable for cases where the iterable is small, my answer becomes more effective if you are working with much larger sequence because there is no copy of parts of the iterable and it would also work when receiving any iterable, even if this does not support slicing.


Explanation

Starting with the line:

args = [iter(iterable)] * n

First of all:

  1. We create an object of the type Iterator using the method iter();
  2. A single element list is created, this element is the iterator created in the above item;
  3. Multiply the list n times for them to be created n references at the same iterator (in this answer better explanation about sequence multiplication).

    >>> [iter("77775698897897236")] * 4
    [<str_iterator at 0x7f07473b4f10>,
     <str_iterator at 0x7f07473b4f10>,
     <str_iterator at 0x7f07473b4f10>,
     <str_iterator at 0x7f07473b4f10>]
    

As you can see in item 3, we have a list with 4 references to the same iterator, as the four point to the same memory address (0x7f07473b4f10).

That is, if I consume 1 item from each reference would be the same as consuming 4 items from the "original iterator".

>>> for iterador in [iter("1234567890")] * 4:
>>>     next(iterador)
1
2
3
4

That’s where the itertools.zip_longest, to consume these references to the same iterator. For when you do:

args = [iter("1234567890")] * 4
zip_longest(*args)

It would be the same as doing:

ref_iter = iter("1234567890")
zip_longest(ref_iter, ref_iter, ref_iter, ref_iter)

And in practice this code consumes the entire iterator of 4 in 4 items. The above code would return:

>>> ref_iter = iter("1234567890")
>>> zip_longest(ref_iter, ref_iter, ref_iter, ref_iter)
[('1', '2', '3', '4'), ('5', '6', '7', '8'), ('9', '0', None, None)]

-2

Adapt to your code

    print([codigo[i:i+4] for i in range(0, len(codigo), 4)]) 
  • 2

    Nelson, you just copied the accepted answer and turned the for into comprehensilist on. There’s nothing you can add that the other answers haven’t addressed yet?

  • @fernandosavio was not my intention to "copy " your code, because your answer is found on other sites, just google. I believe it is the simplest way to solve the above problem, so I have nothing else to add

  • 1

    My comment was not because of code authorship, but because your answer did not add anything to what was already in the other answers. Is there anything that differentiates your answer from the others? Something that the author of the question can learn that has not already been explained in other answers? Get my point?

Browser other questions tagged

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