1

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it's working. Is it possible to print number like 4.7 so instead of printing it like [4,7] it prints out [4.7]?
1

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)

2 Comments

Thank you it's working aswell, but now I'm having a problem when numbers are decimal so instead of printing 3.54 it prints out 3,5,4 is there a command to somehow combine them and put . there it was at the begining
@ElBob, Just change the regex criteria. Check my updated answer. This will work with both number and float.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.