My aim is to print bytes string lines in Python 3, but truncate each line to a maximum width so that it fits the current terminal window.
My first attempt was only
print(output[:max_width]), but this did not work because Python counts e.g. tabs
\t as one character, but the terminal displays them as multiple characters. Also, it would evaluate carriage-returns etc.
Therefore now I have this snippet of code,
line is a bytes string:
output = line.decode(codec, "replace") if max_width: output = "".join(c for c in output if c.isprintable()) print(output[:max_width]) else: print(output)
However, I guess it's pretty slow to refactor each string line this way just to filter out non-printable characters like
\r (and whatever characters I might have forgotten).
Please note that
codec is specified by the user. It might be
utf-16 or any other valid built-in codec.
Can you please suggest me how to improve this code's performance?