Python Forum

Full Version: How to aling the printing statements
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I have below code to print matching start index and end index with aligned columns.
I use below code:

import re
pattern = re.compile('ab')
matcher = pattern.finditer('zxaababaababa')
for match in matcher:
    print("starting index   ", str(match.start()) + " End index ", str(match.end()))
    #print("The matched endstarting index is: ", match.end())
My output is below:
starting index    3  End index  5
starting index    5  End index  7
starting index    8  End index  10
starting index    10  End index  12
but my desired output in 3rd line the columns are not aligned after 10:

starting index    3  End index  5
starting index    5  End index  7
starting index    8  End index  10
starting index    10 End index  12
>>> import re
>>> pattern = re.compile('ab')
>>> matcher = pattern.finditer('zxaababaababa')
>>> for match in matcher:
...     print("starting index   ", str(match.start()).ljust(4,' ') + " End index ", str(match.end()).ljust(4,' '))
...
starting index    3    End index  5
starting index    5    End index  7
starting index    8    End index  10
starting index    10   End index  12
Or use a format string.
import re
pattern = re.compile('ab')
matcher = pattern.finditer('zxaababaababa')
for match in matcher:
    print(f'Starting index {match.start():<2}  End index {match.end():<2}')
Although it's working, but I want to learn how it's working (logic)?
The f'Starting index...' thing is a formatted string literal. It is a new (V3.6) shorthand for the string format command. Text inside the curly brackets is evaluated and replaced. In my example {match.start():<2} is evaluated and then some formatting is applied.

Match.start() becomes '3', then the :<2 says "I want you to be 2 wide and left justified", '3 '. The formatting codes are documented here:
https://docs.python.org/3.8/library/string.html

And you can find more information about fstrings here:
https://realpython.com/python-f-strings/