I am trying to subtract three files that contains number i.e 2849-2948-2312 but each file has some words and because of that I get error of
could not convert string to float: 'TiH'
I am trying to subtract three files that contains number i.e 2849-2948-2312 but each file has some words and because of that I get error of
could not convert string to float: 'TiH'
Converting text that is not float()-convertable gives an exception. You can catch exceptions and return something different and filter the result vor only valid ones:
def safeFloat(word):
try:
return float(word)
except ValueError:
return None
# file.read() gives you a text, so I use a text directly here
text = """Some
42.54
57.93
don't
42.0
work 80/20"""
# convert what can be converted - results contains None
con = [safeFloat(w) for w in text.split()]
print(con)
# filter for non-None
nonNone = [c for c in con if c is not None]
print(nonNone)
to get
[None, 42.54, 57.93, None, 42.0, None, None]
[42.54, 57.93, 42.0]
Checking if a string can be converted to float in Python explain a tangential way to come to similar solutions.