Questions about advanced usage of string formatting

Asked 2 years ago, Updated 2 years ago, 417 views

'''
       3
x     12
--------
      36
'''

I'm trying to express this expression in code. I've tried the bottom four

#try1

a=3
b=12
print('%8d' %a)
print('%-6s%-1d'%('x',b))
print('--------')
print('%8d'%(a*b))
#try2

a=3
b=12
print('%8d' %a)
print('%-5s %-1d'%('x',b))
print('--------')
print('%8d'%(a*b))
#try3

a=3
b=12
print('%8d' %a)
print('%s %6d'%('x',b))
print('--------')
print('%8d'%(a*b))
#try4

a=3
b=12
print('%8d' %a)
print('%s%7d'%('x',b))
print('--------')
print('%8d'%(a*b))

When formatting with minus sign in %-6d absolute value of -6 in numbers (%-6d), while Formatting without - will result in an absolute value of 8 for the numbers.

I don't know why the two are different I'd appreciate it if you let me know!

python formatting string

2022-10-13 01:00

1 Answers

The number after % means the minimum number of characters. %6d and %-6d all have the same number of characters when a number that does not exceed 6 digits, including a minus sign.

However, the minimum number of characters in Try1 and Try2 is 6 or 7, so it seems that the number larger than the corresponding size was not entered during the test. However, depending on the size of the b values in Try1 and Try2, if it exceeds one digit, the string is formed over the minimum number, which seems to have changed the length of the string length.

This does not cause problems in the examples below.

def print_format(data):
    x = '%3d'%(data)
    y = '%-3d'%(data)

    print(x)
    print(y)

    print(len(x))
    print(len(y))

print_format(10)
print_format(-10)
print_format(100)

However, in the following examples, the length is output as 4.

def print_format(data):
    x = '%3d'%(data)
    y = '%-3d'%(data)

    print(x)
    print(y)

    print(len(x))
    print(len(y))

print_format(-100)
print_format(1000)


2022-10-13 01:00

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.