gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:03:13 24 4
gpt4 key购买 nike

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

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'\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

最佳答案

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

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


另一种选择是使用字符串格式并动态组合字符串格式。

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

关于python - 如果每行由空格分隔,如何在多行文本字符串中实现左对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69325743/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com