How to achieve left alignment in a multi-line text string if each line separated by a space?

0

Issue

How to achieve left alignment of the following text? Thanks in advance!

text = """"
\nword1 meanings
\nword123 measings
\nword12345 meanings
"""

expected:

text = """"
\nword1     meanings
\nword123   measings
\nword12345 meanings
"""

I have tried to use re.sub then using ljust, but it does not work.

In [58]: print(re.sub('(\n[\w]+\s*)', r'\1'.ljust(20), text))
"

word1                   meanings

word123                   measings

word12345                   meanings

# or print(re.sub('(\n[\w]+\s*)', r'\1'+' '*(20-len(r'\1')), text))
# the result is same

Solution

You could for example calculate the length of the longest word from the start of the string, and then add the different in with the max length after each word in spaces.

import re

text = """"
\nword1     meanings
\nword123         measings
\nword12345        meanings
"""

maxLen = len(max(re.findall(r"^\S+", text, re.M), key=len))
result = re.sub(r"(\S+)[^\S\r\n]+", lambda m: m.group(1) + ((maxLen + 1) - len(m.group(1))) * " ", text)
print(result)

Output

word1     meanings

word123   measings

word12345 meanings

Python demo


Another option could be making use of string formatting and dynamically assemble the string format.

maxLen = len(max(re.findall(r"^\S+", text, re.M), key=len))
result = re.sub(r"(\S+)[^\S\r\n]+", lambda m: '{{:{}s}}'
                .format(str(maxLen + 1))
                .format(m.group(1)),
                text)
print(result)

Python demo

Answered By – The fourth bird

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More