按 3 个字符将字符串分组到列表中

Group string by 3 character to a List

例如,我有字符串 "25037654",我想按 3 对字符串进行分组。 但是,由于字符串是 8 个字符,并且 8 % 3 不是 0。它有余数。我希望最终列表是 ["25", "037", "654"],第一个索引将只接受余数,例如 1 或 2 个字符

在这种情况下,一种简单的方法是使用 f-string:

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

如果输入不是数字,上述方法将不起作用。然后尝试:

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

我认为这段代码可以满足您的要求。

先获取每个切片的idx,然后将这个字符串切割成每个子字符串。

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']

感谢所有回复和回答我的问题的人。 片刻之后,我 post 我的问题。我找到了答案大声笑

这是漫漫长路,我的版本。谢谢大家

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) ])

结果:

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

你可以试试我的版本:

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