Python中的列文本框
我在一所学校的项目做出的Yahtzee在python(我非常新的语言)工作,我想知道是否有可能,如果是这样,如何有一个文本列出现在命令行中,以显示当他们决定在特定类别中评分某些东西时更新的玩家分数。这是我要打印的内容:Python中的列文本框
print:(''' ╔═══════════╗╔═══════════╗
║ Ones ║║ ║
╠═══════════╣╠═══════════╣
║ Twos ║║ ║
╠═══════════╣╠═══════════╣
║ Threes ║║ ║
╠═══════════╣╠═══════════╣
║ Fours ║║ ║
╠═══════════╣╠═══════════╣
║ Fives ║║ ║
╠═══════════╣╠═══════════╣
║ Sixes ║║ ║
╠═══════════╣╠═══════════╣
║ Total ║║ ║
╠═══════════╬╬═══════════╬
╠═══════════╬╬═══════════╬
║ Three of ║║ ║
║ a kind ║║ ║
╠═══════════╣╠═══════════╣
║ Four of ║║ ║
║ a kind ║║ ║
╠═══════════╣╠═══════════╣
║ Full House║║ ║
╠═══════════╣╠═══════════╣
║ Small ║║ ║
║ Straight ║║ ║
╠═══════════╣╠═══════════╣
║ Large ║║ ║
║ Straight ║║ ║
╠═══════════╣╠═══════════╣
║ Chance ║║ ║
╠═══════════╣╠═══════════╣
║ Yahtzee ║║ ║
╚═══════════╝╚═══════════╝
''')
我想第二列被复制,并根据玩家的得分,他们在每个类别中有什么数量和变量更新。任何想法都会有所帮助。
回答:
用户可以预先设置框中固定长度,然后打印出值,并计算与差异的空间来保存您的结构如下:
box_design_length = 10 # box design length to store character ones = 2
twos = 55
threes = 4596
print('''
╔═══════════╗╔═══════════╗
║ Ones ║║ {0}{1}║
╠═══════════╣╠═══════════╣
║ Twos ║║ {2}{3}║
╠═══════════╣╠═══════════╣
║ Threes ║║ {4}{5}║
╚═══════════╝╚═══════════╝
'''.format(ones, ' '*(box_design_length-len(str(ones))),
twos, ' '*(box_design_length-len(str(twos))),
threes, ' '*(box_design_length-len(str(threes))),
)
)
format()
做字符串格式化 {0}, {1}, {2}...
在format()
传递的参数的数目,其支持所有版本的Python以上2.6
输出:
╔═══════════╗╔═══════════╗ ║ Ones ║║ 2 ║
╠═══════════╣╠═══════════╣
║ Twos ║║ 55 ║
╠═══════════╣╠═══════════╣
║ Threes ║║ 4596 ║
╚═══════════╝╚═══════════╝
如果你知道有python formatting你可以更好的方式做到这一点,如下图所示:
from collections import OrderedDict values = OrderedDict([('Ones', 2), ('twos', 55), ('threes', 4596)]) # store key, value in dictionary
# order dictionary is used to preserve order
def box_printer(value_set, box_design_length):
"""
print values in box
:param value_set: dictionary of key and value to print in box
:param box_design_length: length of box design
"""
count = 0 # initialize count: help to identify first loop or last loop to change box design accordingly
for key, value in value_set.items():
if count == 0: # first loop
print('╔{0}╗╔{0}╗'.format('═'*box_design_length))
count += 1
print('║ {1:^{0}}║║ {2:^{0}}║'.format(box_design_length-1, key, value))
if count >= len(value_set):
print('╚{0}╝╚{0}╝'.format('═'*box_design_length))
else:
print('╠{0}╣╠{0}╣'.format('═'*box_design_length))
box_printer(values, 11)
你会得到这个代码你的愿望输出。
回答:
如果您正在使用Python 3.6,然后f-strings将是理想的。
t = 3 text = (f'''
╔═══════════╗╔═══════════╗
║ Ones ║║ {t} ║
╠═══════════╣╠═══════════╣
║ Twos ║║ ║
╠═══════════╣╠═══════════╣
''')
print(text)
经t变量是用大括号添加并使用的文本变量时转换。
以上是 Python中的列文本框 的全部内容, 来源链接: utcz.com/qa/263758.html