Bolding string using ANSI escape sequence `\033[1m` did not work on Windows
Asked Answered
T

2

1

I want to bold the text in a string.
I used the code
print("\033[1mHello, World!\033[0m"),
but it not work, and the output displays as:
?[1mHello, World!?[0m.

The version of python in my computer is 3.9.13, and I use Windows 11.

I hope output bolded "Hello, World!"

Treillage answered 2/9, 2023 at 7:12 Comment(2)
You need a compatible terminal which can interpret such cases. And use it as expected. In short; you should not use ANSI escape characters (which are not ANSI). You should instead use libraries which check the environment and find if and what escape sequence to use. Check e.g. blessing library, or just the code (which just use standard library: and yes: it is standard library which decide the escape sequence).Heiner
Thanks for your suggestion, blessing library is a good option in my case.Treillage
J
2

Using a standard command prompt?
You can try to call os.system first.

>>> import os
>>> os.system("")
0
>>> print("\033[1mHello, World!\033[0m")
Hello, World!

Hello world! should be bold.

Using os.system will ensure the ANSI escape sequences are processed.

Jilt answered 2/9, 2023 at 7:34 Comment(2)
Thanks a lot, it work well. I also want to know why this method works.Treillage
My understanding it is/was a python bug that was supposed to be fixed but maybe not. A workaround is the os.system command before printing. There are other methods to overcome this but I think it's the simplest for a straight print statement.Jilt
E
0

+1 @moken Yes, your os.system("") suggestion even works to bold text in a Windows 10 cmd.exe terminal where nothing else I tried did. Colored text also works in cmd.exe also as shown below.

from colorama import Fore, Style

os.system("")

def red_text(obj:object) -> str:
    return Fore.RED + Style.BRIGHT + f"{obj}" + Style.RESET_ALL

n_items = 56
print(f"Found {red_text(n_items)} items.")
Especially answered 15/3 at 20:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.