Python 当 ANSI 转义序列字符在字符串中时忽略字符串格式

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

ANSI escape sequence characters 包含在字符串中时,为什么忽略字符串格式?

示例 (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 = '[90m'
    
    if execution_time > 0:
        c = '3[94m'
        endc = '3[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}3[0m')

预期输出为:

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

但它会产生

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

:25s 字符串格式被忽略;我错过了什么?

因为cgreycendc在计算对齐格式时被考虑在内

尝试打印字符串的原始字节。

# ...
    x = f'{cgrey}{elapsed_time_text:25s}{rows_affected_text}3[0m'
    print(x)
    print(x.encode())

结果:

Elapsed Time: 0 secs      (26953 rows affected)
b'\x1b[90mElapsed Time: 0 secs      (26953 rows affected)\x1b[0m'
Elapsed Time: 12 secs (26953 rows affected)
b'Elapsed Time: \x1b[94m12\x1b[0m secs (26953 rows affected)\x1b[0m'