简体   繁体   中英

How to colour a specific character cell in python using ansi escape codes where the character cell location is determined by variables

I would like to be able to colour a character cell in python where the character cell to be coloured is determined by two variables (one for the line one for the column).

I've tried string parsing and string concatenation but I can't work out why they don't work.

sys.std(u"\u033[%d;%dH\u001b[47m\033[0m" % (y, x))

code = 47
sys.stdout.write(u"\u001b[81;23f\u001b[" + str(code) + "m " + RESET )
sys.stdout.write(u"\u001b[" + str(x) + ";23f\u001b[" + str(code) + "m " )

The first one says: SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-4: truncated \\uXXXX escape

The second line works, it colours the character cell at line 81 column 23 grey. But the third line prints "\" at line 81 column 23 instead of outputting a coloured pixel.

I don't really understand why the string concatenation works for the second one and not the third. Ideally, I'd like to be able to change the values 81 and 23 using variables ie x and y.

I've been pondering this for quite a few hours now and would appreciate some insight.

On python 3, the line 3 of your code works without changing. On python 2, you need to cast all string members to unicode :

sys.stdout.write(u"\u001b[" + unicode(x) + u";23f\u001b[" + unicode(code) + u"m " )

The first line seem to have another problem with the escape sequence as \\u033 isn't a valid escape char.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM