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

## 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