Python-将字符串数字转换为浮点
我有以下字符串数值,只需要保留数字和小数。我就是找不到合适的正则表达式Python-将字符串数字转换为浮点,python,regex,typeconverter,Python,Regex,Typeconverter,我有以下字符串数值,只需要保留数字和小数。我就是找不到合适的正则表达式 s = [ "12.45-280", # need to convert to 12.45280 "A10.4B2", # need to convert to 10.42 ] 将字符串中的每个字母字符转换为空字符“” 您可以选择区域设置和正则表达式的组合: import re, locale from locale import atof # or whatever else locale.se
s = [
"12.45-280", # need to convert to 12.45280
"A10.4B2", # need to convert to 10.42
]
将字符串中的每个字母字符转换为空字符“”
您可以选择
区域设置
和正则表达式的组合:
import re, locale
from locale import atof
# or whatever else
locale.setlocale(locale.LC_NUMERIC, 'en_GB.UTF-8')
s = [
"12.45-280", # need to convert to 12.45280
"A10.4B2", # need to convert to 10.42
]
rx = re.compile(r'[A-Z-]+')
def convert(item):
"""
Try to convert the item to a float
"""
try:
return atof(rx.sub('', item))
except:
return None
converted = [match
for item in s
for match in [convert(item)]
if match]
print(converted)
# [12.4528, 10.42]
您还可以删除所有非数字和非点字符,然后将结果转换为浮点:
In [1]: import re
In [2]: s = [
...: "12.45-280", # need to convert to 12.45280
...: "A10.4B2", # need to convert to 10.42
...: ]
In [3]: for item in s:
...: print(float(re.sub(r"[^0-9.]", "", item)))
...:
12.4528
10.42
此处的
[^0-9.]
将匹配除数字或文字点以外的任何字符 那么,您的第一个预期输出值是浮点-267.55还是字符串“12.45-280”?您尝试了什么正则表达式,它们给出了什么结果?尝试了[0-9\.]。
?它将匹配一个数字或句点,后跟零或一个(任何)字符。我认为这将匹配s[0]开头的两个字符,而s[1]中没有一个字符,对吗?编辑您的问题,并显示您希望它做什么-完全正确。数字中只允许有一个点。也可以接受负数的前导减号。@VPfB可能需要考虑的要点,谢谢
In [1]: import re
In [2]: s = [
...: "12.45-280", # need to convert to 12.45280
...: "A10.4B2", # need to convert to 10.42
...: ]
In [3]: for item in s:
...: print(float(re.sub(r"[^0-9.]", "", item)))
...:
12.4528
10.42