Count certain characters in a word in python

2

I'm making a command to help you read a globe.

entrada = int(input("Quantos centimetros no globo: "))
km = entrada * 425
m = km * 1000
cm = m * 100
print(entrada, "centimetros no globo equivalem a:", km, "quilometros", m, 
"metros e", cm, "centimetros.")
input()

Where the command transforms the centimeters of the globe into real numbers (Numeric scale). But often, the M is a half-large number and it would be excellent to turn it into scientific notation. Assuming it's 20,000,000 m, can you create a line that "counts" how many zeros it has in the number and returns a value for me to do the conversion?

    
asked by anonymous 15.12.2017 / 19:37

2 answers

6

You simply display the formatted value using e .

>>> print('{:e}'.format(20000000))
2.000000e+07

If you want to limit the number of decimal places as well, you can do this together with the formatting:

>>> print('{:.1e}'.format(20000000))
2.0e+07

Where .1 indicates the number of decimal places.

Note that the 2.0e+07 notation is the scientific notation accepted worldwide and it is also worth remembering that the dot is used as the decimal separator, not the comma, as we used in Brazil.

    
15.12.2017 / 20:25
1

You can use the rest of the division by 10 to know how many zeros on the right an integer has:

def conta_zeros(n):
  zeros = 0
  while n != 0 and n % 10 == 0: # se não for zero e ainda for divisível por 10
    zeros += 1 # mais um zero :D
    n /= 10 # tira um zero
  return zeros

One way to get away from mathematics would be:

def conta_zeros(n):
  n = str(n) # converte o inteiro para string
  return len(n) - len(n.strip("0")) # retorna a quantidade de caracteres no inteiro original subtraído da quantidade de caracteres do inteiro sem os zeros a direita

The results:

conta_zeros(1)           # retorna 0
conta_zeros(100)         # retorna 2
conta_zeros(3918237000)  # retorna 3

You can implement something like:

n = 3187238000
zeros = conta_zeros(n)
base = str(n).strip("0") # retira os zeros sobrando
print(f"{n} = {base}*10^{zeros}") # imprime 3187238000 = 3187238*10^3

If you want to do this to represent a number in scientific notation, see this answer

    
15.12.2017 / 19:41