我有以下的字符串数值,需要保留数字和小数点。我无法找到正确的正则表达式。
s = [
"12.45-280", # need to convert to 12.45280
"A10.4B2", # need to convert to 10.42
]
我有以下的字符串数值,需要保留数字和小数点。我无法找到正确的正则表达式。
s = [
"12.45-280", # need to convert to 12.45280
"A10.4B2", # need to convert to 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.]
会匹配除数字和英文句点以外的任何字符。
将字符串中的每个字母字符转换为空字符""
import re
num_string = []* len(s)
for i, string in enumerate(s):
num_string[i] = re.sub('[a-zA-Z]+', '', string)
locale
和正则表达式来实现: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]
[0-9\.].?
吗? - alvas一个数字或句点
后面跟着零个或一个(任何)字符
。我认为这将在s[0]的开头匹配两个字符,而不匹配s[1]中的任何字符,对吗?编辑您的问题并准确展示您想要它做什么。 - CAB