简体   繁体   中英

convert a string from a list to a float

I have a list with strings. Some of the strings contain alphabets and some contain numbers. I want to convert one of the strings with numbers in it to a float but getting an error

the list is called x . the 3rd element of the list is numbers. I tried x[2] = float (x[2]) but it gives me :Value error: could not convert string to a float:%" See line 12 of the code where I am comparing float(x[2]) with 100

def file_read(fname):
    i = 0
    content_array = []
    with open(fname, 'r') as f:
        #Content_list is the list that contains the read lines.     

        for line in f:
            content_array.append(line)
            x = content_array[i].split('|')
            i = i + 1
            x[2] = x[2].strip() # to delete any empty spaces
            if float(x[2]) > 50.00:
                print ('got one')
        print x[2]
        print i

file_read('flow.txt')

Around your if statement you can wrap a try/except block, the program will try to convert float(x[2]) to a float, but if it cannot (since its a string) it will execute the except portion of the code.

try:
    if float(x[2]) > 50.0:
        print('got one')
except:
    # do something else, if x[2] is not a float
    pass     # if you don't want to do anything. 

You can use regular expressions to check if it's a number, and then you can safely cast it to float.

import re
rgx = "^\d*\.?\d*$"
if re.match(rgx, x):
    print("it's a number!")
    x = float(x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM