Home > OS >  trying to mutiply results and getting error
trying to mutiply results and getting error

Time:10-28

i'm trying to multiply the result "5,0" but nothing works, can someone explain what i'm doing wrong?

print result is "5,0 5,0 5,0 5,0 5,0 " i used .replace to remove "KM" from result.

import selenium
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
from time import sleep
import pandas as pd
import re


#C:\Users\jefferson\AppData\Roaming\Python\Python39\site-packages\webdriver_manager\drivers


servico = Service(ChromeDriverManager().install())
navegador = webdriver.Chrome(service=servico)
navegador.get("https://www.google.com.br/maps/dir//")


#digitar primeiro endereço

navegador.find_element('xpath', '//*[@id="sb_ifc50"]/input').send_keys("Rimatur Transportes, Rodovia     Curitiba - Ponta Grossa Br-277, Km 2,1875 - Mossunguê, Curitiba - PR, 82305-100")

navegador.find_element('xpath', '//*[@id="sb_ifc50"]/input').send_keys(Keys.ENTER)

#destino

navegador.find_element('xpath', '//*[@id="sb_ifc51"]/input').send_keys("Av. Juscelino Kubitschek De     Oliveira - Ld, 2600 - Cidade Industrial De Curitiba, Curitiba - PR, 81260-900")

navegador.find_element('xpath', '//*[@id="sb_ifc51"]/input').send_keys(Keys.ENTER)


def km():
    sleep(10)
    kmtotal=navegador.find_element('xpath', '/html/body/div[3]/div[9]/div[9]/div/div/div[1]/div[2]/div/div[1]/div/div/div[4]/div[1]/div[1]/div[1]/div[1]/div[2]/div')
    km1 = kmtotal.text
    value = km1.replace('km', '')
    kmprint = value
    a = 5
    print(kmprint * a)
   #kmprint2 = int(float(kmprint))
 #  print(type(kmprint2))
km()`

print result >>> 5,0 5,0 5,0 5,0 5,0 `

CodePudding user response:

kmprint is a string and there is no implicit casting in Python - you need to cast it to another type, e.g. float type to perform arithmetic calculations in Python after cleaning up the string. Otherwise, multiplication performed on a string will return the same string repeated n times.

CodePudding user response:

To elaborate on povk's answer:

km1 = '5,0 km' # this is a string
value = km1.replace('km', '').replace(',', '.') # still a string
value_cast = float(value) # this is a float

value * 5
>>> '5.0 5.0 5.0 5.0 5.0 '

value_cast * 5
>>> 25.0

If in your country decimals are typically written with a comma, you might find is useful to define a small helper function you can reuse later:

def to_float(value: str) -> float:
    # add more code if you also want to remove any letters/extract digits from a string
    return float(value.replace(',', '.'))
  • Related