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

走远了吗. 提交于 2019-12-02 02:15:46

问题


python: extract float from a python list of string( AUD 31.99). I used openpyxl to read from an excel file the amount list. and i saved it in a list but the list is in string form like this:

['31.40 AUD', ' 32.99 AUD', '37.24 AUD']

I need to get the float from the string item list so that i can later save it in a new list to get the total of them.

Desired output:

[31.40, 32.99, 37.24]

I have already tried these:

newList = re.findall("\d+\.\d+", tot[0])
print(newList)

Output:

[31.40]

But How can I use this for all the item elements?

I am new to python, this is just for some work i do, wanted to see the total using python instead of using excel`s find & replace option. thanks


回答1:


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]



回答2:


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]



回答3:


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)



回答4:


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]


来源:https://stackoverflow.com/questions/53276670/python-extract-float-from-a-python-list-of-string-aud-31-99

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