how can i remove all characters in list item after "-" python and convert that item data type to float?

Viewed 61

I have a list of items in python

lst=["2.6","2-3","7-8","9","10-11","1 Year","2 Weeks"]

I have to remove everything after "-"

Expected list i want

lst=[2.6,2.0,7.0,9.0,10.0,"1 Year","2 Weeks"]

How can i achieve ?

4 Answers

There is a way using regular expressions:

import re

def one_elem(elem):
    if re.fullmatch('\d+', elem):
        return float(elem)
    if re.fullmatch('\d+\.\d+', elem):
        return float(elem)
    if re.fullmatch('\d+-\d+', elem):
        return float(elem.split('-')[0])

    return elem

lst=["2.6","2-3","7-8","9","10-11","1 Year","2 Weeks"]
lst = [one_elem(elem) for elem in lst]
lst

Result:

[2.6, 2.0, 7.0, 9.0, 10.0, '1 Year', '2 Weeks']

Create a function to do the conversion:

def convert(value):
    try:
        return float(value.split('-', 1))
    except ValueError:
        return value

Then use it:

result = [convert(value) for value in lst]

Or even:

result = list(map(convert, lst))

For fun, a list comprehension to do both the split and conversion to float (I wouldn't really use this is in a project as it's less than explicit!):

[float(n) if (n:=s.split('-',1)[0]).replace('.','',1).isdigit() else s for s in lst]

NB. requires python ≥3.8.

Output: [2.6, 2.0, 7.0, 9.0, 10.0, '1 Year', '2 Weeks']

lst=["2.6","2-3","7-8","9","10-11","1 Year","2 Weeks"] #your original list
fixedlst = [] # your new fixed list

for stuff in lst:  

if "-" in stuff:
    #from elements that contain - only!

    x = stuff.replace("-", ".").split(".")[0] #getting rid of - to . and removing everything after .
    fixedlst.append(float(x))  #adding it to the new list as float so it adds .0 at the end


if "-" not in stuff:
    #for elements that dont contain -
    
    try:
        fixedlst.append(float(stuff))  # converting all numerical strings to float

    except ValueError:
        fixedlst.append(stuff) # returning non-numerical strings as they are


#I did this in 2 steps so i dont remove the original numbers        

print(fixedlst)

your output would be:

[2.6, 2.0, 7.0, 9.0, 10.0, '1 Year', '2 Weeks']
Related