如果每行由 space 分隔,如何在多行文本字符串中实现左对齐?

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

如何实现下面文字的左对齐?提前致谢!

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

预计:

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

我曾尝试使用 re.sub 然后使用 ljust,但它不起作用。

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

word1                   meanings

word123                   measings

word12345                   meanings

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

您可以拆分行,左对齐第一个单词,右对齐第二个单词,如下所示。

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

如果你有一个多行字符串,你可以像下面那样首先获取行并拆分单词并将它们左右对齐,如下所示。

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

例如,您可以从字符串的开头计算最长单词的长度,然后在空格中的每个单词后添加与最大长度不同的 in。

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)

输出

word1     meanings

word123   measings

word12345 meanings

Python demo


另一个选项可能是使用字符串格式和动态 assemble 字符串格式。

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

例如:

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)