python: extract float from a python list of string( AUD 31.99)

ぃ、小莉子 提交于 2019-12-02 01:00:12

You can use the map function:

inList = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD']
output = list(map(lambda elem: float(elem.split()[0]), inList))
print(output)

Output:

[31.4, 32.99, 37.24]

If you want to get list of values with regex, try

tot = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD']
newList = [float(re.search('\d+\.\d+', fl).group(0)) for fl in tot]
print(newList)
# [31.40, 32.99, 37.24]

but using split seem to be easier solution in this case

tot = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD']
newList = [float(item.split()[0]) for item in tot] 
print(newList)
# [31.40, 32.99, 37.24]

If second substring is always the same ("AUD") you can also try

tot = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD']
newList = [float(item.rstrip(' AUD')) for item in tot] 
print(newList)
# [31.40, 32.99, 37.24]

Is it possible to use a string split instead? I think it would be much simpler

ls1 = ['32.46 AUD', '17.34 AUD']

myFloats = []
for aString in ls1:
    aFloat = float(aString.split()[0])
    myFloats.append(aFloat)

You should consider handling errors. Here is one way for instance:

import re
import math

def float_from_string(str_):
    # Try to extract a floating number, if fail return nan
    r = re.search('\d+\.\d+', str_)
    return float(r.group()) if r else math.nan

tot = ['31.40 AUD', ' 32.99 AUD', '37.24 AUD', ' nonumberhere AUD']
totfloat = [float_from_string(i) for i in tot]

print(totfloat)

Returns:

[31.4, 32.99, 37.24, nan]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!