我有以下字符串數值,並且只需要保留數字和小數。我無法爲此找到正確的正則表達式。Python - 將字符串 - 數字轉換爲浮點數
s = [
"12.45-280", # need to convert to 12.45280
"A10.4B2", # need to convert to 10.42
]
我有以下字符串數值,並且只需要保留數字和小數。我無法爲此找到正確的正則表達式。Python - 將字符串 - 數字轉換爲浮點數
s = [
"12.45-280", # need to convert to 12.45280
"A10.4B2", # need to convert to 10.42
]
轉換每個字母字符的字符串空字符「」
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]
您還可以刪除所有非數字和非圓點字符,然後將結果轉換爲浮點數:
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」? –
你試過了什麼正則表達式,他們給了什麼結果? – CAB
試過'[0-9 \。]。??? – alvas