0

I am working on a school project and for that, I am trying to slice a string equal to the last digit of the string, I need to make sure that each slice is of equal length to the last digit, if it not of equal length then I need to add trailing zeroes

Example: "132567093" should be ['132', '567', '090'] When I try i get ['132', '567', '09']

This is so far the code I have

n = input()
int_n = int(n)
num=int(n)
lastdigit=num%10
s = n[:-1]
print([s[idx:idx+lastdigit] for idx,val in enumerate(s) if idx%lastdigit 
== 0])
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219

2 Answers2

1

To zero-pad on the left, there's a str.zfill method.

By reversing the string, applying zero padding and reversing again, you can achieve this

print([s[idx:idx+lastdigit][::-1].zfill(lastdigit)[::-1] for idx,val in enumerate(s) if idx%lastdigit== 0])

outputs:

['132', '567', '090']

without zfill you can compute the number of characters to add. The formula is ugly but it's faster because it doesn't create 3 strings in the process:

[s[idx:idx+lastdigit]+"0"*(max(0,lastdigit-len(s)+idx)) for idx,val in enumerate(s) if idx%lastdigit== 0]
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

Another way of doing this is to use the zip clustering idiom with a fill value

from itertools import zip_longest as zipl

*digits, length = '132567093'

length = int(length)

print([''.join(t) for t in zipl(*[iter(digits)]*length, fillvalue='0')])
# ['132', '567', '090']

# To sum them together
print(sum(int(''.join(t)) for t in zipl(*[iter(digits)]*length, fillvalue='0')))
# 789

You can also use string formatting:

s='132567093'
length = int(s[-1])
digits = s[:-1]
format_str = "{{:0<{}}}".format(length) # {:0<3}
print([format_str.format(digits[i:i+length]) for i in range(0, len(digits), length)])
# ['132', '567', '090']
print(sum(int(format_str.format(digits[i:i+length])) for i in range(0, len(digits), length)))
# 789
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96