Count certain characters in a word in python

Asked

Viewed 1,295 times

3

I’m making a command to help 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 (Numerical scale). But often, M is a rather large number and it would be excellent to turn it into scientific notation. Assuming it is 20,000,000 m, it is possible to create a line that "counts" how many zeros there are in the number and return me a value, then make the conversion?

2 answers

6

Just display the formatted value using the e.

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

If you want to limit the number of decimals as well, you can do it along with formatting:

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

Where the .1 indicates the number of decimal places.

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

  • Thank you, it was extremely helpful!

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

A 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

Browser other questions tagged

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