2021年1月29日星期五

Python string format ignored when ANSI escape sequence characters are in the string

Why does string formatting get ignored when ANSI escape sequence characters are included in the string?

Example (Python 3.9.1):

execution_times = [0, 12]  for execution_time in execution_times:      affected_row_count = 26953      c = ''      cgrey = ''      endc = ''            if execution_time == 0:          cgrey = '\33[90m'            if execution_time > 0:          c = '\033[94m'          endc = '\033[0m'            rows_affected_text = f' ({affected_row_count} rows affected)'      elapsed_time_text = f'Elapsed Time: {c}{execution_time}{endc} secs'            print(f'{cgrey}{elapsed_time_text:25s}{rows_affected_text}\033[0m')  

Expected output would be:

Elapsed Time: 0 secs      (26953 rows affected)  Elapsed Time: 12 secs     (26953 rows affected)  

but instead it yields

Elapsed Time: 0 secs      (26953 rows affected)  Elapsed Time: 12 secs (26953 rows affected)  

The :25s string formatting is being ignored; what am I missing?

https://stackoverflow.com/questions/65964243/python-string-format-ignored-when-ansi-escape-sequence-characters-are-in-the-str January 30, 2021 at 11:04AM

没有评论:

发表评论