How to remove string characters

Asked

Viewed 74 times

-1

Hello I have the following code:

lista_valores = ["20.000","2.000"]
for valores in lista_valores:
    valor = valores.strip(".000")
    print(valor)

And its result is:

2
2

But my goal is to get the values without the decimal places thus:

20
2

I tried to use the strip but it didn’t work out, how can I do that?

  • 1
  • It would be an option but the variable would be returned as a list, which would not be useful to me

  • 1

    Actually this is your best option, separate into different variables is another problem, but can be solved easily using milhares, unidades = "20.000".split(".") or you can ignore the second part with milhares, _, _ = "20.000".partition("/")

  • 1

    @Paulomarques Com int does not work: https://ideone.com/g3WI3Q

1 answer

1


strip receives the list of characters to be removed from the beginning and end of the string, i.e., you are removing all the zeroes and dots of the end, why "20,000" becomes "2".

If strings represent numbers, then convert them to numerical values using float:

lista_valores = ["20.000","2.000"]
for valores in lista_valores:
    valor = float(valores)
    print(valor)

Only this prints "20.0" and "2.0". If you want to round and eliminate decimals, use round:

lista_valores = ["20.000","2.000"]
for valores in lista_valores:
    valor = round(float(valores))
    print(valor)

Then he prints "20" and "2".

Another option, as indicated in the comments, is to format the value:

lista_valores = ["20.000","2.000"]
for valores in lista_valores:
    print(f'{float(valores):.0f}')

In the case, .0f indicates that the number should be formatted with zero decimal places. See documentation for more details.


Manipulating the string, as suggested by the other answers (which have been deleted), is not ideal, because changing the number of decimals there would not work anymore. Already converting to numbers using the correct functions, you avoid these problems.

  • I understood everything thank you for clarifying

Browser other questions tagged

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