用termcolor.colored打印某些不同颜色的字符串?

时间:2016-06-02 04:30:07

标签: python colors

我想在Python中打印不同颜色的某些字符串。我需要修改代码:

pry

这样当列表中board_p1 = [] board_pc = [] board_size=6 for x in range(board_size): board_p1.append(["[W]"] * board_size) board_pc.append(["[W]"] * board_size) def print_board(board): if board == board_p1: print colored("\n Computers Board: ",attrs=['underline']) for row in board: print " ".join(colored(element,"cyan") if element != "[X]" else colored(element,"red") if element != "[H]" else colored(element,"magenta") for element in row) if board == board_pc: print colored("\n Players Board: ",attrs=['underline']) for row in board_pc: print " ".join(colored(element,"cyan") if element != "[S]" else colored(element,"green") if element != "[X]" else colored(element,"red") if element != "[H]" else colored(element,"magenta") for element in row) 将打印为洋红色时,[H]将显示为红色等,我可以输出如下内容:

enter image description here

我遇到了困难:

[X]

以上述方式打印。

问:如何修改/编辑上面的代码行,这样如果在列表中看到[X]打印为红色,[S]为绿色和洋红色[H]?

1 个答案:

答案 0 :(得分:2)

虽然由于添加了括号,以下内容会正确解析:

print " ".join(colored(element,"cyan") if element != "[S]" else (colored(element,"green") if element != "[X]" else (colored(element,"red") if element != "[H]" else colored(element,"magenta"))) for element in row)

然而,由于条件被否定,我无法判断它是否会产生您问题中示例中描述和描述的映射。

但是从这个描述中我会建议使用这样的字典会更好:

element_colors = {'[W]': 'cyan', '[X]': 'red', '[S]': 'green', '[H]': 'magenta'}

print " ".join(colored(element, element_colors[element]) for element in row)