Posts: 8
Threads: 3
Joined: May 2017
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!
Posts: 1,150
Threads: 42
Joined: Sep 2016
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.
Posts: 8
Threads: 3
Joined: May 2017
Thanks for the quick reply!
Posts: 2,125
Threads: 11
Joined: May 2017
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.
Posts: 687
Threads: 37
Joined: Sep 2016
[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
Posts: 3,458
Threads: 101
Joined: Sep 2016
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 !', '@#$%', '^&*(', ')-=[', "]\\;'", ',./_', '+{}|', ':<>?']
Posts: 8
Threads: 3
Joined: May 2017
(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?
Posts: 3,458
Threads: 101
Joined: Sep 2016
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
\ '
Posts: 2,953
Threads: 48
Joined: Sep 2016
The single \ is there. Just when you print the list Python is representing it like that - see the previous post.
Posts: 687
Threads: 37
Joined: Sep 2016
(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
|