honesty1997 honesty1997 - 1 month ago 7
Python Question

Python output replace not float value

a = raw_input()
a = a.split(',')
def printFormat(file):
for i in range(len(a)-1):
if a[i] != '':
a[i] = float(a[i])
print '%05.1f %05.2f %5d %5d %5d %05.1f %05.1f %5d %5d %05.2f %05.2f %16s'%(a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[9],a[10],a[11])
printFormat(a)


This is my code here.I want to print some values in a good format, but here is the problem.If all the value is float, the code works fine.When one of it is space or something else,there will be an error.I want to replace all none float value to '-' and still in a good format.
Here is the example input:

1.3,,15,18,5,4.1,1.4,98,1,6.53,2.39,9/9/2016 10:00


The output should be:

001.3 - 15 18 5 004.1 001.4 98 1 06.53 02.39 9/9/2016 10:00


Don't know how to replace the none float value with '-' in the middle of the space.

Answer
  • split a like you did
  • split the format too
  • zip them and generate a listcomp using each format against the float-converted value
  • if the value is empty, replace it by the length of the valid field, but dashed (("-"+" "*(len(f % 0.0)-1) issues a dash + computes formatted length minus one and pads with spaces)
  • add last special format in the end
  • join the resulting list with spaces

Here's my solution:

a="1.3,,15,18,5,4.1,1.4,98,1,6.53,2.39,9/9/2016 10:00"
a = a.split(',')
the_format = '%05.1f %05.2f %5d %5d %5d %05.1f %05.1f %5d %5d %05.2f %05.2f %16s'.split()

print(" ".join([f % float(v) if v else "-"+" "*(len(f % 0.0)-1) for v,f in zip(a[:-1],the_format)]+[the_format[-1] % a[-1]]))

result:

001.3 -        15    18     5 004.1 001.4    98     1 06.53 02.39   9/9/2016 10:00
Comments