我到处寻找这个问题的答案,只找到了我问题的一部分。
我在整个过程中对代码进行了注释,以说明哪些是有效的,哪些是无效的,以及
每一行都有多大的错误。提前谢谢。在#
# list_of_numbers is a list with numbers
# like '3.543345354'
#
# I want to change to a number with two places
#
#
# for each item in the list
for idx, value in enumerate(list_of_numbers):
# make sure it is not none
if value != None:
#
# convert to a float - this works
temp_val = float(value)
# test and print the format - yep this works
print("%.2f" % temp_val)
# store in a new variable - works
formatted_number = "%.2f" % temp_val
# check - yep looks good so far. the line blow will print 3.54 etc
print formatted_number
#
# now try to store it back
#
# the below two lines when I try both give me the
# unsupported operand type(s) for +: 'float' and 'str'error
list_of_numbers[idx] = formatted_number
list_of_numbers[idx] = '%s' % formatted_number
#
# the line below give me the error
# float argument required, not str
list_of_numbers[idx] = '%f' % formatted_number
#
# so from the above error formatted_number is a string.
# so why cant I set the variable with the string
#
# the ONLY thing that works is the lone below but I
# dont want an integer
#
list_of_numbers[idx] = int(float(value ))