0

I am trying to get abs of float, which is initially stored in str as:

for q in range(0, len(moms), 1):
    print("mom types", type(moms[q]))
    out.write(abs(float(moms[q]))+" ")
out.write("\n")

which gives error:

mom types <class 'str'>
Traceback (most recent call last):
  File "s2gen.py", line 192, in <module>
    out.write(abs(float(moms[q]))+" ")
TypeError: unsupported operand type(s) for +: 'float' and 'str'

I am not regular in python, but it seems, the string to float is correct, as from here or here. Not sure, what is going wrong here.

Community
  • 1
  • 1
BaRud
  • 3,055
  • 7
  • 41
  • 89

1 Answers1

3

You can't add a float value and a str value; you have to convert the result of the abs function back to a str explicitly before adding a space to it.

out.write(str(abs(float(moms[q]))) + " ")
chepner
  • 497,756
  • 71
  • 530
  • 681