Search code examples
pythonjoinstring-formattingjustify

Is there is way to justify substrings while performing join operation


I have to replace a word in a multiline text at specific location specified by a line number and word number in this line. All words all aligned in columns.

I'm using an algorithm where I'm finding word by it's coordinates.

I'm fetching a line at specified line number, splitting it in separate substrins and replacing a word at specified location with another word. Then I do join (" ".join() ) and writing the modified line back into a file. My problem is i'm loosing words alignment in modified line. How can I justify and join at the same time? (Other words in a line also lose alignment, not just modified word)

I think I could do it if I have used a little bit different approach by splitting a line just at the location of the word to be modified, but I did not realized that I will lose alignment after splitting a line at word boundaries.


Solution

  • You can apply formatting (with format() or str.format()) inside a list comprehension before joining:

    ''.join([format(el, '<10') for el in list_of_strings])
    

    Demo:

    >>> list_of_strings = ['foo', 'barbaz', 'spam-ham']
    >>> ''.join([format(el, '<10') for el in list_of_strings])
    'foo       barbaz    spam-ham  '
    

    < left-aligns, > right-aligns and ^ centers the text in the given width (10 in the above example). For more detail on how formatting works, see the format specification documentation.

    Demo with right-adjustment to 4 spaces:

    >>> list_of_strings = ['foo', 'ba', 'a']
    >>> ''.join([format(el, '>4') for el in list_of_strings])
    ' foo  ba   a'