简体   繁体   English

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

[英]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?当字符串中包含ANSI 转义序列字符时,为什么字符串格式会被忽略?

Example (Python 3.9.1) :示例(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:预期的 output 将是:

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; :25s字符串格式被忽略; what am I missing?我错过了什么?

Because cgrey , c and endc are taken into account when calculating the alignment format.因为计算 alignment 格式时考虑了cgreycendc

Try to print raw bytes of the string.尝试打印字符串的原始字节。

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

Result:结果:

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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