Reputation: 417
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?
Upvotes: 0
Views: 326
Reputation: 82765
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
Upvotes: 4
Reputation: 12015
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
Upvotes: 5