简体   繁体   中英

How to make specific parts of a text line indented properly?

I use python print() function to print component name, its current version and latest version as follows:

for component in component_list:

print("%s \t current ver: %s \t latest ver: %s" % (name, current_version, latest_version))

The component name can differ in its length, which makes the sentence parts not be indented properly.

bla      current ver: 0x05   latest ver: 0x05


blabla1      current ver: 0x06   latest ver: 0x06


blablablabla     current ver: 0x08   latest ver: 0x0e

How can I make the above printed as follows:

bla              current ver: 0x05   latest ver: 0x05


blabla1          current ver: 0x06   latest ver: 0x06


blablablabla     current ver: 0x08   latest ver: 0x0e

Thanks,

If maxLength is the maximum length of the name in your list, eg:

# I don't know how you extract name from component so this might be incorrect
maxLength = max(len(component.name) for component in component_list)

Then you can use the following to correctly format your code:

print("{:{width}} \t current ver: {} \t latest ver: {}".format(
    name, current_version, latest_version, width = maxLength)
)

Explanation:

>>> '{:<20}'.format('Hello World!') # Add spaces to the right to reach 20 characters
'Hello World!        '
>>> '{:>20}'.format('Hello World!') # Add spaces to the left
'        Hello World!'
>>> '{:20}'.format('Hello World!') # Use default alignment for the type of object
'Hello World!        ' # For string it is left aligned

Then, instead of using a raw 20 , you can use another variable to specify the width:

>>> '{:<{width}}'.format('Hello World!', width = 20)
'Hello World!        '

Check str.format documentation for complete documentation of the Format Specification Mini-Language .

  • Iterate over all the list to find the maximum length of the left component
  • use this value (eg round it to the next 4 character) to determine the starting column for the second component (say n )
  • Iterate again over the list, this time printing the first component, (n-len(first_component)) spaces and then the second component

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