Group string by 3 character to a List

Viewed 84

for example, I have string "25037654", and I want to Group the string by 3. but, since the string is 8 character, and 8 % 3 is not 0. it have remainder. and I want the final List is ["25", "037", "654"], the first Index will only accept the remainder, for example 1 or 2 character

5 Answers

I think this code may satisfy your requirement.

First get the idx of every slice, then cut this string to each substring.

str_num = "25037654"
idx = [len(str_num)%3+3*i for i in range(len(str_num)//3+1)]
print(idx) # [2, 5, 8]
if(idx[0]!=0):
    idx = [0]+idx
res = [str_num[idx[i]:idx[i+1]] for i in range(len(idx)-1)]
print(res) # ['25', '037', '654']

One easy way, in this case, is to use f-string:

s = "25037654"
output = f"{int(s):,}".split(',')
print(output) # ['25', '037', '654']

The above won't work if the input is not numeric. Then try:

leading = len(s) % 3
output = ([s[:leading]] if leading else []) + [s[i:i+3] for i in range(leading, len(s), 3)]

Thanks everyone who respond and answer My Question. after a few moments I post my question. I found the answer LoL

it's the Long Way, my version. thanks Guyss

s = "25037654"
if len(s) % 3 == 2:
   fn = s[0:2]
   xx = s[2:len(s)]
   group = list(map(''.join, zip(*[iter(xx)]*3)))
   final = fn + " " + " ".join(group)
elif len(s) % 3 == 1:
   fn = s[0:1]
   xx = s[1:len(s)]
   group = list(map(''.join, zip(*[iter(xx)]*3)))
   final = fn + " " + " ".join(group)
elif len(s) % 3 == 0:
   group = list(map(''.join, zip(*[iter(s)]*3)))
   final = " ".join(group)

print(final) # 25 037 654
t = "25037654555"
i, j =  divmod(len(t), 3) # i - int part, j - remainder
print([t[:j]] + [t[j+(i-1)*3:j+i*3] for i in range(1,i+1) ])

Result:

['25', '037', '654', '555']

You can try my version:

s = "25037654"
rem = len(s)%3
lst = []

i = 0
while i < len(s)-2:
    if i == 0:
        lst.append(s[:rem])
        i+=rem
    else:
        lst.append(s[i:i+3])
        i+=3
Related