Python print жирный шрифт

Как напечатать жирный текст на Python?

дубликат цветного текста в терминальных приложениях в Unix . Много ссылок в ответах. Этот ответ написан на C, но легко переводится на Python.

9 ответов

class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' print color.BOLD + 'Hello World !' + color.END 

Лично я считаю, что это самый полезный ответ. Использование здесь: stackoverflow.com/questions/287871/…

Мне нравится, что вы не просто выделили жирным шрифтом, а создали целый класс, чтобы они могли ссылаться и помогать всем пользователям просматривать. Спасибо.

И чтобы вернуться к нормальной жизни:

Эта страница является хорошей ссылкой для печати в цветах и ​​шрифтах. Перейдите в раздел «Установить графический режим:»

И обратите внимание, что это не будет работать во всех операционных системах, но вам не нужны никакие модули.

В прямом программировании компьютера нет такой вещи, как «печать жирного текста». Давайте немного подкрепляемся и понимаем, что ваш текст представляет собой строку байтов, а байты — это просто пучки бит. Для компьютера, здесь ваш «привет» текст, в binary.

0110100001100101011011000110110001101111 

Каждый бит или ноль немного. Каждые восемь бит являются байтом. Каждый байт является в строке, подобной той, что находится в Python 2.x, одной буквенной/числовой/пунктуационной позиции (называемой символом). Так, например:

01101000 01100101 01101100 01101100 01101111 h e l l o 

Компьютер переводит эти биты в буквы, но в традиционной строке (называемой строкой ASCII) ничего не выделяется жирным шрифтом. В строке Unicode, которая работает немного по-другому, компьютер может поддерживать символы международного языка, такие как китайские, но опять же нет ничего, что могло бы сказать, что какой-то текст выделен жирным шрифтом, а какой-то текст нет. Также нет явного шрифта, размера текста и т.д.

В случае печати HTML вы все равно выводите строку. Но компьютерная программа, считывающая эту строку (веб-браузер), запрограммирована так, чтобы интерпретировать текст типа this is bold как «это жирный«, когда он преобразует вашу строку букв в пиксели на экране. Если бы весь текст был WYSIWYG, потребность в HTML сама была бы смягчена — вы бы просто выделили текст в своем редакторе и смели вместо него, вместо того, чтобы печатать HTML.

Другие программы используют разные системы — многие ответы объясняют совершенно другую систему для печати жирного текста на терминалах. Я рад, что вы узнали, как делать то, что хотите, но в какой-то момент вам захочется понять, как работают строки и память.

Каким бы неудовлетворительным ни казался этот ответ, вероятно, именно он наиболее правильно отвечает на заданный вопрос . Это вообще не вопрос Python, а вопрос о том, что делает рендеринг .

Читайте также:  Css изменить класс элемента

Дело в том, что каждый, кто интересуется ответом на этот вопрос, понимает двоичный код и то, как он используется для представления строк. Мы заинтересованы в том, как использовать python, чтобы текст выглядел жирным, на что дан ответ выше. Этот ответ слишком педантичен.

Отъезд colorama. Это не обязательно помогает в смелости. но вы можете сделать раскрашенный вывод как на Windows, так и на Linux и контролировать яркость:

from colorama import * init(autoreset=True) print Fore.RED + 'some red text' print Style.BRIGHT + Fore.RED + 'some bright red text' 

Существует очень полезный модуль для форматирования текста (полужирный, подчеркивание, цвета..) в Python. Он использует curses lib, но он очень прост в использовании.

from terminal import render print render('%(BG_YELLOW)s%(RED)s%(BOLD)sHey this is a test%(NORMAL)s') print render('%(BG_GREEN)s%(RED)s%(UNDERLINE)sAnother test%(NORMAL)s') 

ОБНОВЛЕНО:

Я написал простой модуль с именем colors.py, чтобы сделать это немного более питоническим:

import colors with colors.pretty_output(colors.BOLD, colors.FG_RED) as out: out.write("This is a bold red text") with colors.pretty_output(colors.BG_GREEN) as out: out.write("This output have a green background but you " + colors.BOLD + colors.FG_RED + "can" + colors.END + " mix styles") 

ImportError: No module named terminal ImportError: No module named render На самом деле это единственный сайт, который я могу найти о модуле «терминала». Пожалуйста, дополните.

Приведенная выше ссылка раньше содержала модуль terminal , но они перенаправили страницу. Вот код, кэшированный Google.

В любом случае, я сделал свой собственный модуль Python, чтобы решить эту проблему, проверьте @minerals 😉

Источник

How to Print Bold Text in Python

To print bold text in Python, you can use the built-in “ANSI escape sequences” to make text bold, italic, or colored. The text can be printed using the particular ANSI escape sequences in different formats.

The ANSI escape sequence to print bold text in Python is: ‘\033[1m’.

print("This is bold text looks like:",'\033[1m' + 'Python' + '\033[0m')

Print Bold Python Text

You can see from the output that Python is bold. Although, my console is zsh. So it displays white color. But you can think of it as bold text.

Using the termcolor

The termcolor is a package for ANSI color formatting for output in the terminal with different properties for different terminals and specific text properties. We will use bold text attributes in this function. The colored() function gives the text a specific color and makes it bold.

We first install the termcolor module.

Next, we use pip to install packages in Python.

python3 -m pip install termcolor

Now, let’s write the colored text.

from termcolor import colored print(colored('python', 'red', attrs=['bold']))

You can count the above text as red-colored text in the output.

Using the color Class

In this approach, we will create a color class. Then, the ANSI escape sequence of all the colors is listed in the class. Then, to print the color of our choice, we can select any colors.

class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' print("The output is:" + color.BLUE + 'Python 3!')

Using the color Class

Using the Colorama package

To work with the Colorama package, you need to install the package.

python3 -m pip install colorama

It is a cross-platform for colored terminal text. In addition, it makes ANSI works under Microsoft Windows for escape character sequences.

from colorama import init from termcolor import colored init() print(colored('Python 3 !', 'green', 'on_red'))

Using the colorama package

We used a Colorama module with termcolor to print colored text on the Windows terminal.

Читайте также:  Java строка плюс число

Calling init() on Windows would filter ANSI escape sequences out of every other text sent to stdout or stderr, replacing them with Win32 equivalent calls. In addition, the colored() function will color the specified string green.

Using Prompt_toolkit package

Prompt_toolkit includes a print_formatted_text() function that is compatible (as much as possible) with the built-in function. It also supports colors and formatting.

from prompt_toolkit import print_formatted_text, HTML print_formatted_text(HTML('The text is bold')) print_formatted_text(HTML('The text is italic')) print_formatted_text(HTML('The text is underlined'))

Источник

Print Bold Text in Python

  1. Print Bold Text in Python Using the ANSI Escape Sequence Method
  2. Print Bold Text in Python Using the color Class
  3. Print Bold Text in Python Using the termcolor Method
  4. Print Bold Text in Python Using the colorama Package
  5. Print Bold Text in Python Using the simple_color Package

This article will discuss some methods to print bold text in Python.

We can use built-in ANSI escape sequences for making text bold, italic or colored, etc. By using the special ANSI escape sequences, the text can be printed in different formats. The ANSI escape sequence to print bold text is: ‘\033[1m’ . To print the bold text, we use the following statement.

print("The bold text is",'\033[1m' + 'Python' + '\033[0m') 

Here, ‘\033[0m’ ends the bold formatting. If it is not added, the next print statement will keep print the bold text.

This method creates a color class. ANSI escape sequence of all the colors is listed in the class. To print the color of our own choice, we can select any of the colors.

The complete example code is given below.

class bold_color:  PURPLE = '\033[95m'  CYAN = '\033[96m'  DARKCYAN = '\033[36m'  BLUE = '\033[94m'  GREEN = '\033[92m'  YELLOW = '\033[93m'  RED = '\033[91m'  BOLD = '\033[1m'  UNDERLINE = '\033[4m'  END = '\033[0m'  print("The output is:" + color.BOLD + 'Python Programming !' + color.BLUE) 

The termcolor is a package for ANSI color formatting for output in the terminal with different properties for different terminals and certain text properties. We will use bold text attributes in this function. The colored() function gives the text the specific color and makes it bold.

The complete example code is given below.

from termcolor import colored print(colored('python', 'green', attrs=['bold'])) 

It is a cross-platform for colored terminal text. It makes ANSI works under MS Windows for escape character sequences. To use this package, you must install it in your terminal by the following command. If you have not installed it, then the code will not work properly.

pip install colorama conda install -c anaconda colorama 

The complete example code is given below:

from colorama import init from termcolor import colored init() print(colored('Python Programming !', 'green', 'on_red')) 

We use the colorama module with termcolor , to print colored text on the Windows terminal. Calling init() on Windows would filter ANSI escape sequences out of every other text sent to stdout or stderr , replacing them with Win32 equivalent calls. The colored() function will color the specified string in the green color.

Читайте также:  Php simplexml add cdata

We must install this package by the following command.

pip install simple_colours 

It is the simplest method to print bold text in Python.

The complete example code is given below:

from simple_colors import * print(green('Python', 'bold')) 

Related Article — Python Print

Источник

Bold formatting in Python console

But I am getting the output as [‘\x1b[1mfsdfs’, ‘\x1b[1mfsdfsd’, ‘\x1b[1mgdfdf’] But the required output is [‘kumar’,’satheesh’,’rajan’] How to format the list elements in bold using python ?

Please consider using a different variable name for your list.. list is not an enforced keyword but it will give you unforeseeable problems if you use that as your variable name..

You are making the bold for square bracket also if it is really want print bold before printing the array

3 Answers 3

You need to also specify END = ‘\033[0m’ :

list = ['kumar','satheesh','rajan'] BOLD = '\033[1m' END = '\033[0m' for each in list: print('<><><>'.format(BOLD, each, END)) 

To make the list itself bold like [‘kumar’, ‘satheesh’, ‘rajan’]:

for each in list: print(each) 

I did not downvote, and I know that it will work. But code only answers are considered as poor on SO. Explaining why it works that way will greatly improve your answer.

Your code will print all outputs in bold even if an item doesn’t prefix with the escape string because it didn’t ends with ‘\033[0m’.

I need the output to be enclosed in list. Inside the list only, the bold letters are not coming @Kalyan

Kalyan gave a possible way, but failed to explain the why.

When ask Python to print a list, it will output the start and end of list markers( [] ) and a representation of all the items of the list. For a string, it means that non printable characters will be escaped.

There is little you can do except printing separately the items

or build a unique string with join:

string_to_output = '[' + ', '.join(lst) + ']' print(string_to_output) 

By the way, as explained by Austin ‘\x01b[1m is an sequence to ask an ANSI compatible terminal to pass in bold mode, so you must at a time revert to normal mode with ‘\x01b[0m .

And remember: ANSI is common in Linux terminal emulations, but it is still far from being universal. Just try to use export TERM=tvi950 before using it (and google for vt100 and tvi950 to understand more).

Источник

Оцените статью