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

Time:09-26

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

CodePudding user response:

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

CodePudding user response:

For example:

import re

text = """
word1 meanings
word123 measings
word12345 meanings
"""

def repl(match): return match.group(1).ljust(10)   match.group(2)
text = re.sub(r'^(\w )  (\w )$', repl, text, flags=re.MULTILINE)
print(text)

CodePudding user response:

You can split the line and left align the first word and right align the second word as below.

print(text.split()[1].ljust(20) text.split()[2].rjust(20))

if you have a multi line string you can do like below initially get the lines and split the words and align them as left and right as below.

for strings in text.strip().split('\n'):
    if len(strings) > 1:
        print(strings.split()[0].ljust(20)   strings.split()[1].rjust(20))
  • Related