I have a list of strings in python which are in form of an arithmetic problem. So:
p_list = ['32 5', '4 - 1', '345 2390']
I would love each of the list to be arranged in this manner
32 4 345
5 - 1 2390
---- --- ------
So essentially i want the numbers to be right aligned and four spaces between each expression.
I tried doing something like this
final = f"{final} {problem_list[key]['operand1']}\n{problem_list[key]['operator']} {problem_list[key]['operand2']}"
but i got this instead
213
4 3234
4 3
- 3 5
7
thanks in advance
CodePudding user response:
If your objective is to print out the equations, this code arranges them in your desired way:
p_list = ['32 5', '4 - 1', '345 2390']
top = ""
mid = ""
bot = ""
sep = " " * 4
for eq in p_list:
chars = eq.split()
width = len(max(chars, key=len)) 2
top = chars[0].rjust(width) sep
mid = chars[1] chars[2].rjust(width - 1) sep
bot = "-" * width sep
print(top, mid, bot, sep="\n")
Out:
32 4 345
5 - 1 2390
---- --- ------
CodePudding user response:
There are many ways to achieve this. Here's one:
plist = ['32 5', '4 - 1', '345 2390']
spaces = ' ' * 4
def parts(plist):
return [e.split() for e in plist]
def widths(plist):
return [max(map(len, e)) 2 for e in parts(plist)]
def get_tokens(plist, idx):
if idx == 0:
return [f'{e:>{w}}' for (e, _, _), w in zip(parts(plist), widths(plist))]
if idx == 1:
return [f'{s}{n:>{w-1}}' for (_, s, n), w in zip(parts(plist), widths(plist))]
return ['-' * w for w in widths(plist)]
for idx in range(3):
print(spaces.join(get_tokens(plist, idx)))
Output:
32 4 345
5 - 1 2390
---- --- ------
CodePudding user response:
Try this:
p_list = ['32 5', '4 - 1', '345 2390']
up= []
down=[]
for op in p_list:
new = op.split(' ')
up.append(new[0] ' '*4)
if new[1] == '-':
down.append(str(0 - int(new[-1])) ' '*4)
else:
down.append(' ' new[-1] ' '*3)
for index,value in enumerate(up):
print(value, end=' ')
print('')
for index,value in enumerate(down):
print(value, end=' ')
# 32 4 345
# 5 -1 2390