简体   繁体   English

将字符串转换为int或float(如果可能)*

[英]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. 我正在编写一个Python脚本,用于从频繁丢失的不稳定无线连接中接收数据。 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). 我需要将接收到的字符串转换为各种int和float,但是通常数据会乱码,导致出现诸如“ int无效的文字”(或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. 数据以逗号分隔的int和float值的形式出现,但是通常会缺少一些数字和/或逗号和/或行尾。

I'm looking for a function that (sorry for the reference - I'm old) resembles the val(x$) function of the Commodore 64: 我正在寻找一个类似于Commodore 64的val(x $)函数的函数(对不起参考,我已经老了):

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. 我想我可以通过try-catch运行每个数字,但这似乎有点过头了。 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 您可以使用re.match从字符串的开头提取数字或小数点,然后转换为浮点数

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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