Home > Mobile >  How to compare only part of text that contains digits?
How to compare only part of text that contains digits?

Time:12-30

So I have list made by with

driver.find_elements_by_*

and for example while printed with .text this list looks like this:

17.4K gems
8.5K gems
11.4K gems
9.7K gems

Can I somehow compare only part with number without creating new list with extracted numbers so it will work like code below?

if gems[x].text > '10.5':
   print(gems[x].text)

CodePudding user response:

You can try this:

Example list:

name_list = ["17.4K gems", "8.5K gems", "11.4K gems", "9.7K gems"]

for name in name_list:
    split_name = name.split("K")
    print(split_name[0])

Output:

17.4
8.5
11.4
9.7

Then, you can compare like:

if split_name[0] > '<some value>':
    <condition>

CodePudding user response:

One way to do it is by splitting your strings at the 'K' letter, e.g. using

import re
re.split('K', element)

and compare the content of the first part with 10.5. Note that this will be a string so conversion to float will be required first: float(re.split('K', element)[0]).

Finally if you want to write this in a comprehensive way, you will end up with a new list, that can be printed in different ways.

Example:

myList=['17.4K gems', '9.8K gems', '0.9K gems', '15.3K gems']
for el in [item for item in myList if float(re.split('K',item)[0]) > 10.5]:
  print(el)

which returns

17.4K gems
15.3K gems

CodePudding user response:

try this to get list of numbers

name_list = ["17.4K gems", "8.5K gems", "11.4K gems", "9.7K gems"]
nums = [float(item.split('K')[0]) for item in name_list]
print(nums)
  • Related