0

I'm writing a Python script for receiving data from a shaky wireless connection with frequent dropouts. I need to convert the received strings to various ints and floats, but often the data is garbled, resulting in errors like "invalid literal for int" (or float).

The data comes in as a string of comma separated int and float values, but often, some numbers and/or commas and/or line endings will be missing.

I'm looking for a function that (sorry for the reference - I'm old) resembles the val(x$) function of the Commodore 64:

print val("3")
3

print val("234xyz")
234

print val("55.123456*******")
55.123456

I guess I could run every single number through a try-catch, but that seems a little over the top. Isn't there a function for this?

3
  • 1
    What about cases such as "122xxxx23232"? What do you expect it to be? Commented Aug 5, 2018 at 9:01
  • I'd expect that to return 122. Commented Aug 5, 2018 at 9:02
  • 1
    There is no built-in function for this, you'll have to build your own (using regex for example, as suggested by Sunitha's answer) Commented Aug 5, 2018 at 9:05

2 Answers 2

5

You can use re.match to extract the digits or decimal point from the beginning of the string and then convert to float

>>> import re
>>> s = "55.123456*******"
>>> float(re.match(r'[\d.]*', s).group())
55.123456
Sign up to request clarification or add additional context in comments.

1 Comment

I'm somewhat surprised that Python does not contain a built-in function that does this. However, your suggestion does exactly what I need. Thanks! :-)
4

Using Regex.

import re

def getInt(val):
    m = re.match(r"\d+\.?\d*", val)
    return m.group() if m else None

print(getInt("3"))
print(getInt("234xyz"))
print(getInt("55.123456*******"))

Output:

3
234
55.123456

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.