I have found different answers elsewhere that will work, but I can't quite figure out why my code is not working properly. What I am trying to do is take a list of alphabetical characters and join the first 4, second 4, third 4, etc. elements. I'll paste an example below to make this more clear.
If given the following list: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'I', 'M', 'N', 'O', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
I want to combine the elements so that I receive the following output:
['ABCD', 'EFGH', 'IJKL', 'IMNO', 'QRST', 'UVWX', 'YZ']
I thought I identified a good solution on my own, but it doesn't seem to work. What I tried was:
x = 'ABCDEFGHIJKLIMNOQRSTUVWXYZ'
y = 4
def wrap(string, max_width):
slist = [char for char in string]
new = []
for i in range(0, len(slist), max_width):
new.append(''.join(slist[i:max_width]))
return new
wrap(x, y)
The output that I get from this is:
['ABCD', '', '', '', '', '', '']
I would appreciate if if someone could help me identify what is wrong and help me fix it. Like I said previously, I have found other answers online that will do what I want, but I really want to figure out where I went wrong here.
It looks like there was logic issues in the for loop:
You were trying to add items between i:max_width. However max_width is always 4 and when i is > 4 you get no items return as it is an empty string. Instead I have added max_width to meaning the grouping is always the same size:
x = "ABCDEFGHIJKLIMNOQRSTUVWXYZ"
y = 4
def wrap(string, max_width):
slist = [char for char in string]
new = []
for i in range(0,len(slist),max_width):
new.append(''.join(slist[i:(i+max_width)]))
return new
print(wrap(x, y))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With