简体   繁体   中英

Formatting Integers

I want to understand the logic behind the outputs of the below print statements.

x = 345
print ("%06d"%x)
print ("%-06d"%x)

The first statement would as expected prefix the number of zeroes required to make the total length as 6. The output is 000345 which I understand.

But the output of the second print statement is 345. How come? What is purpose of "-" operand?

minus means align to left.

You will see it when you add another element in print -

print("%06d"%x,  'a') 
print("%-06d"%x, 'a')

Result

000345 a
345    a

See: PyFormat.info

Basically, the minus and the leading zero specify conflicting requirements. Python arbitrarily picks the minus as the winner.

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