I want to only get text from the element and then only to get numbers from that element.
global textelement
textelement = (WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='text-nowrap text-truncate']")))).text
The text I get looks something like this
U(4) Leiknir
I want one variable to only contain text from the element and one variable to only contain numbers from that text so the output looks like this :
Text only
U Leiknir
and
Numbers only
4
Is it possible to do this?
CodePudding user response:
Yes, You can do this by using regex and filter function like this.
import re
def filter_str(s):
res_num = [int(match) for match in re.findall(r"\d ", s)]
res_str = "".join(filter(lambda x: not x.isdigit(), s))
return res_num, res_str
s = "U(4) Leiknir"
a, b = filter_str(s)
print("Numbers: ", a , "\nStr: ", b)
Output:
Numbers: [4]
Str: U() Leiknir
CodePudding user response:
Yes you can do that by using regex.
Import re
textelement ="U(4) Leiknir"
number=re.findall(r'\d ', textelement)[0]
print(number)
chars = " ".join(re.findall("[a-zA-Z] ", textelement))
print(chars)
output:
4
U Leiknir
Update:
textelement ="U(3.45) Leiknir"
number=re.findall(r'(\d (?:\.\d )?)', textelement)[0]
print(number)
chars = " ".join(re.findall("[a-zA-Z] ", textelement))
print(chars)