Reputation: 9
I want divide a 8-digit number into parts with a 4 digit. pls help
def div4(a, n = 4):
return [a [i*4: (i + 1) * 4] for i in range (len(a) // n)]
i tried this but it wont work
Upvotes: 0
Views: 60
Reputation: 363586
You can use stdlib divmod
:
>>> divmod(12345678, 10**4)
(1234, 5678)
Generalizing this idea:
>>> def div(a, n=4):
... if a < 0:
... result = div(-a, n)
... result[0] *= -1
... return result
... p = 10 ** n
... results = []
... while a >= p:
... a, b = divmod(a, p)
... results.append(b)
... results.append(a)
... return results[::-1]
...
>>> div(12345678, 4)
[1234, 5678]
>>> div(123456789012, 4)
[1234, 5678, 9012]
>>> div(123456789012, 2)
[12, 34, 56, 78, 90, 12]
Upvotes: 1
Reputation: 36680
If you want to use strings and slices to solve this:
def parts(m, n=4):
return [int(s[start:start+piece_length])
for s in (str(m),)
for piece_length in (len(s) // n,)
for i in range(n)
for start in (i * piece_length,)]
parts(12345678)
# [12, 34, 56, 78]
parts(12345678, 2)
# [1234, 5678]
Upvotes: 0