简体   繁体   中英

Convert string to int or float *if possible*

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM