我有一個 python 中的字串串列,它們是算術問題的形式。所以:
p_list = ['32 5', '4 - 1', '345 2390']
我希望每個串列都以這種方式排列
32 4 345
5 - 1 2390
---- --- ------
所以基本上我希望數字右對齊,每個運算式之間有四個空格。
我試著做這樣的事情
final = f"{final} {problem_list[key]['operand1']}\n{problem_list[key]['operator']} {problem_list[key]['operand2']}"
但我得到了這個
213
4 3234
4 3
- 3 5
7
提前致謝
uj5u.com熱心網友回復:
如果您的目標是列印出方程式,則此函式可以按照您想要的方式排列它們:
def arithmetic_format(eq_list, sep = 4):
top = mid = bot = ""
sep = " " * sep
for eq in eq_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
return f"{top}\n{mid}\n{bot}"
p_list = ['32 5', '4 - 1', '345 2390']
answer = arithmetic_format(p_list)
print(answer)
出去:
32 4 345
5 - 1 2390
---- --- ------
uj5u.com熱心網友回復:
有很多方法可以實作這一點。這是一個:
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)))
輸出:
32 4 345
5 - 1 2390
---- --- ------
uj5u.com熱心網友回復:
嘗試這個:
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533918.html
標籤:Python细绳
上一篇:根據用戶輸入從字串中洗掉字符
下一篇:如何將第一個字符轉換為小寫
