How to print a Python operation by adding zero to the left?

Asked

Viewed 289 times

4

a = int(input('Número: '))
b = int(input('Número: '))
c = a / b
print(c)

If I assign A = 10; B = 5

print will show 2, I wonder if there is some kind of format that allows print to show 02?

Thank you.

  • Do you want to display 02 for an integer number? What if your division generates a real number, like 2.5? What would you display?

  • Sorry, my question was misspelled, I confused some things, now it’s updated

3 answers

5

If you want the print() double-digit output, for example 02, you can use the function .format():

>>> c = 2
>>> print('{:02}'.format(c))
    02

The problem scored by @Jeanextreme002 is valid. If you pass a float, eg: c = 2.3, the result of print() will be 2.3.

4

Format the expression into a fstring:

a = int(input('Número: '))
b = int(input('Número: '))
c = a / b

#define a largura mínima em 2 caracteres, preenchendo com 0 a direita
#remove ponto decimal se a mantissa for 0
print(f'{c:02g}') 

Exit:

Número: 10
Número: 5
02

Reference Mini format specification language.

2

It’s impossible to get the value 02 in the form of float or int, because in Python and even in your own calculator, the value 02 will be converted into only 2.

To add zero to the left, you must turn your dice into string, concatenating "0" with the string value. Example:

a = int(input('Número: '))
b = int(input('Número: '))
c = a / b

c = "0" + str(c) # Formata o valor

print(c)

But think about it, what would happen if the result were 5.7 for example? Would you like the formatting to be 05.7? It would be a little strange not?

There is another way to format the value and even better, which is using the string method format, thus:

c = "{:02}".format(c)

The difference between the first form I presented and this, is that zero is added only if necessary. See the example below:

c = 12

print("0" + str(c))       # 012
print("{:02}".format(c))  # 12

Note: You updated your question by changing the values of A and B, to imply that you would only do operations where the result was integer. The problem is that in Python, all divisions return values of type float .

That means performing this operation:

>>> 10 / 5

The result would be 2.0. If you want to take that floating point value, you must convert it to int, thus:

int(10 / 5)
10 // 5 # É possível também utilizar "//" para divisões inteiras
  • Bro... why did you deny the answer now? I’m fucked ;-;

  • I don’t know who turned you down or why. But your answer seems to be pretty cool. + 1 then.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.