Answer the question
In order to leave comments, you need to log in
How to allow multiple zeros to be written before a non-zero number?
Hello. I just can’t find how to do this:
I have a string, let’s say
I need to convert this variable to a numeric value without losing zeros:
s_num = '0001'
int(s_num) # 0001 как полноценное число, с которым можно работать, но при такой записи сбрасываются нули
int(s_num) + 1 # мне нужно получить число 0002
Answer the question
In order to leave comments, you need to log in
s_num = "0001"
s = str(int(s_num) + 1).zfill(len(s_num))
print(s)
It is forbidden. Yes, and what's the point?
If you need to display this number with zeros, then "%04d" % s_num
after any arithmetic operations.
something out of a vacuum. But let's say I would do this:
1/ would count the number of zeros from the beginning of the string.
2/ would cut them off and turn the remaining number into an int
3/ added-multiplied-divided-what else is there
4/ would translate the result back into a string
5/ add the number of zeros that I would have received in paragraph 1
5-1/ if need to cut zeros when going through the order (units - tens - hundreds, etc.), then I would write something like a loop that looks at how many times the number was divided by 10 completely. and then by this number would reduce the number of zeros from item 1
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question