简体   繁体   中英

Python formatted output as float of empty string

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

aa = ''
ab = 23
out_str = ''.join(('%6.0f' % var if var!='' else ' '*6) for var in (aa, ab))
print out_str

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM