[英]Termcolor returning strange string of characters
我正在尝试构建我自己的 Wordle 版本,但我被困在这里。 这部分代码的目的是在匹配 position 和密码的字母时将相应的字符着色为绿色,在匹配字母但不匹配 position 时将其着色为黄色。密码中不包含的字符是'吨彩色。
from termcolor import colored
secret = "widow"
def color(word):
if word[0] == secret[0]:
word = word.replace(word[0], colored(word[0], 'green'))
if word[0] == secret[1] or secret[2] or secret[3] or secret[4]:
word = word.replace(word[0], colored(word[0], 'yellow'))
if word[1] == secret[1]:
word = word.replace(word[1], colored(word[1], 'green'))
if word[1] == secret[0] or secret[2] or secret[3] or secret[4]:
word = word.replace(word[1], colored(word[1], 'yellow'))
if word[2] == secret[2]:
word = word.replace(word[2], colored(word[2], 'green'))
if word[2] == secret[1] or secret[0] or secret[3] or secret[4]:
word = word.replace(word[2], colored(word[2], 'yellow'))
if word[3] == secret[3]:
word = word.replace(word[3], colored(word[3], 'green'))
if word[3] == secret[1] or secret[2] or secret[0] or secret[4]:
word = word.replace(word[3], colored(word[3], 'yellow'))
if word[4] == secret[4]:
word = word.replace(word[4], colored(word[4], 'green'))
if word[4] == secret[1] or secret[2] or secret[3] or secret[0]:
word = word.replace(word[4], colored(word[4], 'yellow'))
return word
print(color("woiky"))
在此示例中,我希望“woiky”打印出绿色“w”(因为 woiky 和 widow 都以“w”开头)、黄色“i”和黄色“o”(因为“widow”包含两者“i”和“o”,但不在这些位置),而是打印:[33m[[0m33m[33m[[0m[33m[[0m0m33m[33m[[0m33m[33m[[0m[33m[[ 0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m[33m[[ 0m33m[33m[[0m[33m[[0m0m0m0m[33m[[0m33m[33m[[0m[33m[[0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m[33m[[0m33m[33m[[ 0m[33m[[0m0m0m32mw[33m[[0m33m[33m[[0m[33m[[0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m[33m[[0m33m[33m[[0m[33m[[ 0m0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m0m[33m[[ 0m33m[33m[[0m[33m[[0m0m33m[33m[[0m33m[33m[[0m[33m[[0m0m[33m[[0m33m[33m[[0m[33m[[0m0m0m0moiky
而且所有的“[”字符都是黄色的。
这应该以更聪明的方式做你想做的事。 我不想下载termcolor
,所以我提供了一个替代品。
#from termcolor import colored
secret = "widow"
def colored(a,b):
return( f"<{b}>{a}</{b}>" )
def color(word):
build = []
for i,letter in enumerate(word):
if letter == secret[i]:
build.append( colored(letter, 'green'))
elif letter in secret:
build.append( colored(letter, 'yellow'))
else:
build.append( letter )
return ''.join(build)
print(color("woiky"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.