Python print red color

How to print colored text in Python?

We all want to make our content look attractive and well-readable to our users. For this, Python users can use some built-in modules to print the colored text output of the script in the terminal.

Users can generate colored text output using different ways, such as using the termcolor Module, Colorama Module, and ANSI Escape Sequence. This article will briefly discuss the three methods mentioned above to print colored text in Python.

Method 1: Using the Termcolor Module in Python:

The Termcolor module is a python module that helps to format ANSII Color for output in the terminal. All a user needs to do is to install the termcolor module and use it in the Python script.

import sys from termcolor import colored, cprint text = colored('Hey, this is me', 'blue', attrs=['reverse', 'blink']) print(text)

Explanation:

In the above code snippet, we have used the termcolor module to print the text with the required color. In the output console, the interpreter shows the color blue.

Another example of the termcolor module is:

import sys from termcolor import colored, cprint text = colored('This is Python', blue, attrs=['reverse', 'blink']) print(text) cprint('Hello, World!', 'green', 'on_red') def print_red_on_cyan(x): return cprint(x, 'red', 'on_cyan') print_red_on_cyan('This, is, Python') print_red_on_cyan('Hey, Python!') for i in range(20): cprint(i, 'blue', end=' ') cprint("Alert!", 'green', attrs=['bold'], file=sys.stderr)

Explanation:

Читайте также:  Drop database postgresql python

Here, we have used the built-in module of Python with for loop to print the numbers from 0 to 19 and create colored text in Python.

Method 2: Generate colored text using the Colorama module:

Colorama module is a Cross-platform API for printing colored text in Python. Users can use it to display colored output in the console and can do coding using Colorama’s constant shorthand for ANSI escape sequences.

The built-in module can change the background and the foreground color of any text, which the Python interpreter displays in the console.

Users first have to import the functions, namely, init() , which help in initializing the module by setting the autoreset to «True,» so they do not have to reset it manually. The Fore function provides the Foreground text object, the Back function sets the Background Object, and Style for Style Object.

Code Snippet:

from colorama import Fore, Back, Style print(Fore.BLACK + 'some black text') print(Back.BLUE + 'and with a blue background') print(Style.DIM + 'here are some dim text') print(Style.RESET_ALL) print('back to normal now')

Explanation:

Using the colorama built-in module, we are importing three Python functions and using these functions to print colored text. These are Fore, Back, and Style.

Code Snippet:

from colorama import init from termcolor import colored init() print(colored("Hey, this is cyan Python", "cyan")) print(colored("Hey, this is yellow Python", "yellow")) print(colored("Hey, this is magenta Python", "magenta")) print(colored("Hey, this is green Python", "green")) print(colored("Hey, this is blue Python", "blue")) print(colored("Hey, this is red Python", "red"))

Explanation:

Here, in the above code snippet, we have used the two built-in modules in Python, colorama, and termcolor.

Method 3: Using ANSI Code to print colored text in Python:

Users can also use the ANSI Escape Sequences or Codes to print colored texts in Python. These are special strings that change the working of the internal terminal.

A typical example compared with the ANSI Code would be the \n character, which is a New Line sequence. When users use this in the code, the interpreter does not print it in the console but prints a new line in the output.

The interpreter generates a colored text on the terminal based on ANSI Escape sequences.

Code Snippet:

def prRed(skk): print("\033[91m <>\033[00m" .format(skk)) def prCyan(skk): print("\033[96m <>\033[00m" .format(skk)) def prGreen(skk): print("\033[92m <>\033[00m" .format(skk)) def prLightGray(skk): print("\033[97m <>\033[00m" .format(skk)) def prYellow(skk): print("\033[93m <>\033[00m" .format(skk)) def prLightPurple(skk): print("\033[94m <>\033[00m" .format(skk)) def prBlack(skk): print("\033[98m <>\033[00m" .format(skk)) def prPurple(skk): print("\033[95m <>\033[00m" .format(skk)) prCyan("This is Python") prGreen("Ruby") prYellow("Hey, this is Python") prRed("HTML") prGreen("C++")

Explanation:

The above code snippet shows how to use the ANSI Escape sequences to print the colored text with different color combinations.

In this tutorial, we have gone over how to print colored text in Python output console for the characters users send off to the stdout stream.

Also, we have explored the different methods; and their code snippets, showing how they works and using the built-in functionality Python offers, as well as how to use the Colorama and Termcolor Built-in module. The first two methods are the efficient ones.

  • Python Training Tutorials for Beginners
  • Addition of two numbers in Python
  • Python vs PHP
  • Python Continue Statement
  • Python Uppercase
  • Python map()
  • Polymorphism in Python
  • Inheritance in Python
  • Python Enumerate
  • Python New 3.6 Features
  • Python input()
  • Python String Contains
  • Python eval
  • Python Range
  • Install Opencv Python PIP Windows
  • Python String Title() Method
  • Id() function in Python
  • Python Split()
  • Reverse Words in a String Python
  • Ord Function in Python

Источник

Цветной вывод текста в Python

Всем привет сегодня я хотел рассказать вам «Как сделать цветной вывод текста в Python?» это даже может сделать не опытный человек не имея каких-то знаний. Поэтому если вам интересно то продолжайте читать и тогда все поймете.

C помощью встроенных средств языка

На Python с помощью ANSI-код можно делать цвет, фон и т.д. Это очень мощный и удобный инструмент, с его помощью программист может напрямую определять цвет текста. ANSI коды работают на большинстве дистрибутивов Linux, но не поддерживаются консолью операционной системы Windows до Windows 10.

Изменять цвет текста с помощью ANSI кодов можно разными способами, например, использоваться функции или даже написать свой класс-обёртку для ANSI.

Использовать ANSI коды просто, для этого нужно знать базовый синтаксис и сами коды. Разбор на примере кода «\033[31m\033[43m»:

  • «033[» — обозначение того, что дальше идет какой-то управляющий цветом код.
  • 37m — это код цвета а именно красный.
  • 43m — это код цвет фона для текста.

Именно через этот ANSI-код мы можем делать текст разноцветным, не забывайте ставить «» иначе будет ошибка.

Давайте сделаем вывод текста на консоле через функции.

def out_red(text): print("\033[34m<>".format(text)) out_red("ПРИВЕТ")

Через print() мы задали цвет текста «ПРИВЕТ» синим цветом. Также можно добавить фон и стиль текста все в одну строку.

print("\033[3m\033[33m\033[41m<>\033[0m".format("Htua_0111100000"))
  • \033[3m — отвечает за стилб текста в данном случае это курсив.
  • \033[33m — отвечает за цвет текста.
  • \033[41m — отвечает за цвет фона.
  • <> — заменит на «Htua_0111100000»
  • \033[0m — отвечает за сброс к начальным значениям.

Вобщем вот целая таблица с кодами цвета, фона и стилей.

Сброс к начальным значениям

Смена цвета фона с цветом текста

Цветной вывод текста в Python через библиотеку Colorama

Этой библиотекой тоже можно сделать цветной текст. Достаточно просто знать код и все. Для того чтобы начать работать нужно просто установить библиотеку pip install colorama потом можно начать работать с этой библиотекой. Создайте файл colorama.py и можно приступать к написанию кода.

from colorama import init, Fore from colorama import Back from colorama import Style init(autoreset=True) print(Fore.BLUE + 'some red text') print(Back.WHITE + 'and with a green background') print(Style.BRIGHT + 'and in dim text') print(Style.RESET_ALL) print('back to normal now')

Вывод текста через Colorama

  1. Cначала импортируем init, Back, Style то есть все необходимые нам функции для вывода текста на консоль.
  2. Стоит обратить внимание на функцию init . Если её забыть запустить, то не будет поддерживаться вывод на Windows 10.
  3. print(Fore.BLUE + ‘some red text’) — это задает цвет текста также вы можете поменять на красный (RED) или зеленный (GREEN) и т.д.
  4. print(Back.WHITE + ‘and with a green background’) — это задает фон текста
  5. print(Style.BRIGHT + ‘and in dim text’) — стиль текста
  6. print(Style.RESET_ALL) — сброс всех стилей
  7. print(‘back to normal now’) — обычный текст

Цветной текст через библиотеку termcolor

Это тоже вторая библиотека отвечающее за цвет фон и так далее. pip install termcolor

from termcolor import colored, cprint print(colored('Привет мир!', 'red', attrs=['underline'])) print('Привет, я люблю тебя!') cprint('Вывод с помощью cprint', 'green', 'on_blue')

Импортируем colored и cprint, и пишем print(colored(‘Привет мир!’, ‘red’, attrs=[‘underline’])) тут вобще намного легче чем предыдущая attrs = [‘underline’] задает стиль текста. Следущее сpint(‘Вывод с помощью cprint’, ‘green’, ‘on_blue’) — это функция отвечает за цвет текста и фон. сpint(‘Ваш любимый текст’, ‘цвет текста’, ‘фон текста’)

Вывод

В общем, благодаря ANSI-кодом, библиотека colorama и termcolor можно создавать ваши любимые тексты, кстати можно с этой темой можно создавать мини викторины или что то другое. Я надеюсь на то что вам понравилось эта статья и надеюсь в будущем я продолжу писать все больше и больше статей на разные темы. Спасибо за внимание!

Источник

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