Python Forum
Separating a string into evenly sized elements in a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Separating a string into evenly sized elements in a list
#1
Hey everyone! I'm very new to python, and this is really stumping me.

So let's say I have a list containing every character that someone could type on a keyboard, and for some reason I want to separate them by fours. For example:

chars ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 !@#$%^&*()-=[]\;',./_+{}|:<>?"
would become

chars =['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx', 'yzAB', 'CDEF', 'GHIJ', 'KLMN', 'OPQR', 'STUV', 'WXYZ' #etc]
I have tried inserting commas and then splitting the string using .split(','), but the problem is that the .split function also splits where any commas were in the original string of characters. Also, since the string of characters includes all characters (except for fancy ones like Σ, ç, á, etc), I can't use any other symbol in the .split function.

for x in range(4, int(1.25*len(chars)-1), 5): # The fancy math here accounts for the extra characters that were added from the extra commas.
    chars.insert(x, ',')
chars = ''.join(chars)
split = chars.split(',')
print(message)
Is there any easy function or method that lets the user divide strings or group lists into equally sized groups?

Thanks!
Reply
#2
Hi! I found this solution online, if you don't mind using an extra module for it:
https://stackoverflow.com/a/21351295
If you do mind it, the answer below one I linked should do.
Reply
#3
Thanks for the quick reply!
Reply
#4
The solutions on StackOverflow works fine with Sequences, which have a length and index access.
If you've for example a set or some iterable without known length, you can't use len and index access.

In this case, you can use a generator. This example is more advanced and not easy to understand.
So I commented it a little bit. The return statement were added in Python 3.3. Before
StopIteration was often used to exit a generator. With a return statement you can
exit a generator without problems. In Python 3.7 it'll raise a RuntimeWarning, when raising
StopIteration.

def chunker(iterable, size):
    # make an iterator of the iterable
    # then you can use next(iterator) to get the next element
    # if the iterator is exhausted (end reached), it raises a StopIteration exception
    iterator = iter(iterable)
    # the iterator is True until it's exhausted.
    # this is the condition to leave the while loop
    while iterator:
        # use a list, to append the yielded elements
        # the variable size defines how many elements you take
        # per chunk 
        chunk = []
        for _ in range(size):
            # we know that at a point the iterator is exhausted and will
            # raise an eception. We must catch this exception to handle it
            try:
                # get the next element from iterator
                element = next(iterator)
            except StopIteration:
                # something is in chunk, it'll yield the chunk
                if chunk:
                    yield chunk
                # return from a generator raises a StopIteration
                # don't use here raise StopIteration, because it will be RuntimeError
                # in Python 3.7.
                return
            else:
                # if no exception is raised, we have a new element to add it to the chunk
                chunk.append(element)
        # A for-loop in Python has a else clause, which is executed, when the
        # for loop got a StopIteration. In this case, the StopIteration
        # comes from the range object
        else:
            yield chunk
            # make a new empty chunk list
            chunk = []
This will generate a new chunked list:
import string
list(chunker(string.printable, 4))
If you just run chunker(string.printable, 4), it'll return instantly a generator.
The built-in list function consumes the generator, which acts as an iterable.

Hopefully this not too hard to understand.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#5
[chars[4*i:4*i+4] for i in range((len(chars)+3)/4)]
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply
#6
Would a simple while loop work for this?

>>> chars ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 !@#$%^&*()-=[]\;',./_+{}|:<>?"
>>> chunks = []
>>> while chars:
...   chunk, chars = chars[:4], chars[4:]
...   chunks.append(chunk)
...
>>> chars
''
>>> chunks
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx', 'yzAB', 'CDEF', 'GHIJ', 'KLMN', 'OPQR', 'STUV', 'WXYZ', '1234', '5678', '90 !', '@#$%', '^&*(', ')-=[', "]\\;'", ',./_', '+{}|', ':<>?']
Reply
#7
(Jun-13-2017, 05:17 PM)nilamo Wrote: Would a simple while loop work for this?

>>> chars ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 !@#$%^&*()-=[]\;',./_+{}|:<>?"
>>> chunks = []
>>> while chars:
...   chunk, chars = chars[:4], chars[4:]
...   chunks.append(chunk)
...
>>> chars
''
>>> chunks
['abcd', 'efgh', 'ijkl', 'mnop', 'qrst', 'uvwx', 'yzAB', 'CDEF', 'GHIJ', 'KLMN', 'OPQR', 'STUV', 'WXYZ', '1234', '5678', '90 !', '@#$%', '^&*(', ')-=[', "]\\;'", ',./_', '+{}|', ':<>?']

That seems to work just fine, but the 20th chunk "]\\;'" has 5 characters in it instead of 4. This also occurs with the other methods of "chunking" that I have tried. I know \ is a special character in strings, but I can't understand why or how to fix its duplication. Any explanation?
Reply
#8
The backslash is an escape character.  It's combined with different other characters to mean different things.  \n, for example, is a newline.  It's always combined with something to mean something else.  If you actually want just a backslash by itself, you need a second backslash to escape it.  If you print it out, the extra backslash doesn't exist.

>>> chars = "x \n \\ \'"
>>> chars
"x \n \\ '"
>>> print(chars)
x
\ '
Reply
#9
The single \ is there. Just when you print the list Python is representing it like that - see the previous post.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#10
(Jun-14-2017, 12:50 AM)kennybassett Wrote: That seems to work just fine, but the 20th chunk "]\\;'" has 5 characters in it instead of 4. This also occurs with the other methods of "chunking" that I have tried. I know \ is a special character in strings, but I can't understand why or how to fix its duplication. Any explanation?
This is the whole difference between repr() and str().
Unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.
Your one-stop place for all your GIMP needs: gimp-forum.net
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  unable to remove all elements from list based on a condition sg_python 3 377 Jan-27-2024, 04:03 PM
Last Post: deanhystad
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 427 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Checking if a string contains all or any elements of a list k1llcod3 1 1,023 Jan-29-2023, 04:34 AM
Last Post: deanhystad
  How to change the datatype of list elements? mHosseinDS86 9 1,910 Aug-24-2022, 05:26 PM
Last Post: deanhystad
  ValueError: Length mismatch: Expected axis has 8 elements, new values have 1 elements ilknurg 1 5,013 May-17-2022, 11:38 AM
Last Post: Larz60+
  How to get evenly-spaced datetime tick labels regardless of x-values of data points? Mark17 4 5,097 Apr-04-2022, 07:10 PM
Last Post: Mark17
  Why am I getting list elements < 0 ? Mark17 8 3,031 Aug-26-2021, 09:31 AM
Last Post: naughtyCat
  Looping through nested elements and updating the original list Alex_James 3 2,070 Aug-19-2021, 12:05 PM
Last Post: Alex_James
  Extracting Elements From A Website List knight2000 2 2,182 Jul-20-2021, 10:38 AM
Last Post: knight2000
  Make Groups with the List Elements quest 2 1,936 Jul-11-2021, 09:58 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020