0

I have a string which looks like this :

'< 5s' or '< 0.5s'

And i'm trying to extract the 'duration' from the string. I already have this :

a = '< 5s'
b = int(list(filter(str.isdigit, a))[0])
print(b)

but if i use '< 0.5s' it returns me 0. How can i include the , with the number ?

1
  • 1
    looks like a job for regex Commented Jul 9, 2019 at 14:45

4 Answers 4

2

With simple regex:

import re

s = '< 0.5s'
dur = re.search(r'-?\d+(\.\d+)?', s).group()
print(dur)   # 0.5
Sign up to request clarification or add additional context in comments.

Comments

1
import re
b = re.sub("[^\d\.]", "", a)

Comments

1

A simple b = float(a[2:-1]) should do the trick, if you are certain that the string is always formatted exactly as shown in your example.

Comments

0

You can use regex, maybe something like this:

#!/usr/bin/python3
import re
inp="< 0.5s 5s -12z34 -6.7s"
for i in re.findall("-?\d+\.\d+|-?\d+", inp):
    print(i)

Comments

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.