0
aa = ''

out_str = '%6.0f' % aa

print out_str

Is there a way to print an empty string with the formatting shown above? The reason why I need this is because the variable aa can sometimes store an actual float and other times it will be empty. But i do need to output it in the specified format. float(aa) does not work on an empty string.

EDIT:

How about the following?

aa = ''
ab = 23

out_str = '%6.0f%6.0f' % (aa,ab)

print out_str

EDIT: In above example, aa = '', ab=23 would have to print six spaces, followed by 23 with four leading spaces

7
  • Fair warning: Don't ever edit the main part of your question, especially if someone provided an answer for it. Edits should be done post-main body. Questions not in line with the original question should be done in another post. I rolled back your edit and added in your new query. Commented Apr 14, 2015 at 1:41
  • sorry, will take care. Commented Apr 14, 2015 at 1:44
  • Is it possible for one of aa or ab to be valid and the other to be invalid, printing only the valid one? Commented Apr 14, 2015 at 1:51
  • unfortunately not, i have to print both. for whichever variable is invalid i have to print empty string.... Commented Apr 14, 2015 at 1:55
  • So, aa = '', ab=23 would have to print six spaces, followed by 23 with four leading spaces? Commented Apr 14, 2015 at 1:59

1 Answer 1

3
aa = ''
ab = 23
out_str = ''.join(('%6.0f' % var if var!='' else ' '*6) for var in (aa, ab))
print out_str
Sign up to request clarification or add additional context in comments.

5 Comments

thanks! can your solution work if there are other elements to print in that string?
It would be better to clean up your data structure so that it only contains numbers that you'd like to print, rather than having to deal with it during printing.
the idea is to print an empty string if input data is missing.
Maybe you could validate the input data before saving it, tossing out any improper (empty) inputs?
thanks! as per my comment above: unfortunately not, i have to print both. for whichever variable is invalid i have to print empty string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.