Python removing special character from string not working

62 Views Asked by At

Yesterday I wrote a script which scraped a value from a webpage, and then removed two special characters ('.' and '€') from the scraped string, so it could then be converted to integer format. Today, nonetheless, the code isn't replacing the '€' sign.

The value I get from the webpage is '5.000 €', and to replace the two characters I use the code:

amt = driver.find_element_by_class_name('example-val').text
amt = int(amt.replace('.', '').replace('€', ''))

I have already tried using re.sub, without results:

amt = re.sub('.|€', '', amt)

I don't know whether this is the best approach to convert the string to integer format, but it's what I came up with.

Any help would be greatly appreaciated!

1

There are 1 best solutions below

0
Joshua Varghese On BEST ANSWER

In a more simpler way try this:

amt = driver.find_element_by_class_name('example-val').text
amount=''
for i in amt:
    if i in '0123456789':
        amount+=i
amount=int(amount)

As a One-Liner:

amt = driver.find_element_by_class_name('example-val').text
#Either:
amt = int( ''.join(filter(lambda i: i.isdigit(), amt)))
#or:
amt = int(re.sub("\D", "", amt))