0

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' 
Mmm
  • 3
  • 3
  • Do you have only integers in your files or both integers and floats? – Daweo May 11 '22 at 11:52
  • Welcome to Stack Overflow. "could not convert string to float: 'TiH'" In your own words, what should the result be when you try to convert this string to a float? Why? If you do not want that attempt to happen, did you try to figure out why it happens? Please read [ask] and https://ericlippert.com/2014/03/05/how-to-debug-small-programs/; this is not a debugging service, and "any help is much appreciated" is [not a question](https://meta.stackoverflow.com/questions/284236). – Karl Knechtel May 11 '22 at 11:57

1 Answers1

1

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.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • thanks for the clarification . Best Regards – Mmm May 11 '22 at 12:41
  • Do you think I have to change the string in last line f.write(str(CHGCAR1_ints[i] - CHGCAR2_ints[i] - CHGCAR3_ints[i])) TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType' – Mmm May 11 '22 at 12:43
  • @Must print whatever lists you get from your conmverted files. Check if they have the same lenghts. You still need to filter out the Nones (see `nonNone`) from the list you get. If all lists have the same length and contain only numbers you should be fine. – Patrick Artner May 11 '22 at 12:46