N
N
nochangez2020-05-28 02:42:14
Python
nochangez, 2020-05-28 02:42:14

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 как полноценное число, с которым можно работать, но при такой записи сбрасываются нули

For example, I need to add the number 1 to it: Tell me, how can I do this?
int(s_num) + 1 # мне нужно получить число 0002

Answer the question

In order to leave comments, you need to log in

4 answer(s)
I
ishmatov_rus, 2020-05-28
@nochangez

s_num = "0001"
s = str(int(s_num) + 1).zfill(len(s_num))
print(s)

G
galaxy, 2020-05-28
@galaxy

It is forbidden. Yes, and what's the point?
If you need to display this number with zeros, then "%04d" % s_numafter any arithmetic operations.

S
Sergey Ilyin, 2020-05-28
@sunsexsurf

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

A
AlexBoss, 2020-05-28
@AlexBoss

Why not just look at len(a), convert to int, perform all the necessary operations and then do rjust?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question