Как выровнять текст при выводе в python
Нужно чтобы при выводе в консоль, текст отображался примерно таким образом:
[text1 ]: hello.
[text23 ]: hello..
[text123 ]: hello.
[text0 ]: hello...
Чтобы количество пробелов было в зависимости от текста в квадратных скобках, и всё что после двоеточия было в один столбец. Как это можно реализовать проще?
Ответы (3 шт):
Автор решения: videx
→ Ссылка
listText = ['text1','text11','text111','text1111','1234567891011515151']
listText2 = ['test','test','test','test','ga']
lenElementsMass = []
for i in range(len(listText)):
lenElementsMass.append(len(listText[i]))
lenMass = len(listText)
max = int(max(lenElementsMass)) + 2
for i in range(lenMass):
text = "[" + listText[i] + "]"
while True:
if len(text) < max:
text = text[0:-1] + " " + text[-1]
else:
break
print(text + " " + listText2[i])
вывод:
[text1 ] test
[text11 ] test
[text111 ] test
[text1111 ] test
[1234567891011515151] ga
Автор решения: Pavel Durmanov
→ Ссылка
In [23]: samples = ["test1", "test12", "test123"]
In [24]: max_indent = len(max(samples, key=len)) + 1
In [25]: for sample in samples:
...: print(f"[{sample:<{max_indent}}]: hello")
...:
[test1 ]: hello
[test12 ]: hello
[test123 ]: hello
Автор решения: Shamus Rezol
→ Ссылка
Код
prefixes=\
( "text1",
"text12",
"text123",
"text0")
messages=\
( "hello.",
"hello..",
"hello.",
"hello...")
width=max(map(len, prefixes))
for p, m in zip(prefixes, messages):
print("[%s]: " % p.ljust(width), m, sep='')
Примечание
- В строке
[text123 ]: hello.я посчитал пробел послеtext123лишним, но его можно добавить (width += 1). map(len, prefixes)- все длиныprefixes(<map object at ...>)