E.g:
print "hello"
What should I do to make the text "hello" bold?
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)
Use this:
print '\033[1m' + 'Hello'
And to change back to normal:
print '\033[0m'
This page is a good reference for printing in colors and font-weights. Go to the section that says 'Set graphics mode:'
And note this won't work on all operating systems but you don't need any modules.
You can use termcolor for this:
sudo pip install termcolor
To print a colored bold:
from termcolor import colored
print(colored('Hello', 'green', attrs=['bold']))
For more information, see termcolor on PyPi.
simple-colors is another package with similar syntax:
from simple_colors import *
print(green('Hello', ['bold'])
The equivalent in colorama may be Style.BRIGHT.
In straight-up computer programming, there is no such thing as "printing bold text". Let's back up a bit and understand that your text is a string of bytes and bytes are just bundles of bits. To the computer, here's your "hello" text, in binary.
0110100001100101011011000110110001101111
Each one or zero is a bit. Every eight bits is a byte. Every byte is, in a string like that in Python 2.x, one letter/number/punctuation item (called a character). So for example:
01101000 01100101 01101100 01101100 01101111
h e l l o
The computer translates those bits into letters, but in a traditional string (called an ASCII string), there is nothing to indicate bold text. In a Unicode string, which works a little differently, the computer can support international language characters, like Chinese ones, but again, there's nothing to say that some text is bold and some text is not. There's also no explicit font, text size, etc.
In the case of printing HTML, you're still outputting a string. But the computer program reading that string (a web browser) is programmed to interpret text like this is <b>bold</b> as "this is bold" when it converts your string of letters into pixels on the screen. If all text were WYSIWYG, the need for HTML itself would be mitigated -- you would just select text in your editor and bold it instead of typing out the HTML.
Other programs use different systems -- a lot of answers explained a completely different system for printing bold text on terminals. I'm glad you found out how to do what you want to do, but at some point, you'll want to understand how strings and memory work.
This depends if you're using Linux or Unix:
>>> start = "\033[1m"
>>> end = "\033[0;0m"
>>> print "The" + start + "text" + end + " is bold."
The text is bold.
The word text should be bold.
There is a very useful module for formatting text (bold, underline, colors, etc.) in Python. It uses the curses library, but it's very straightforward to use.
An example:
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')
I wrote a simple module named colors.py to make this a little more pythonic:
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")
print '\033[1m Your Name \033[0m'
\033[1m is the escape code for bold in the terminal.
\033[0m is the escape code for end the edited text and back default text format.
If you do not use \033[0m then all upcoming text of the terminal will become bold.
Check out Colorama. It doesn't necessarily help with bolding... but you can do colorized output on both Windows and Linux, and control the brightness:
from colorama import *
init(autoreset=True)
print Fore.RED + 'some red text'
print Style.BRIGHT + Fore.RED + 'some bright red text'
Install the termcolor module
sudo pip install termcolor
and then try this for colored text
from termcolor import colored
print colored('Hello', 'green')
or this for bold text:
from termcolor import colored
print colored('Hello', attrs=['bold'])
In Python 3 you can alternatively use cprint as a drop-in replacement for the built-in print, with the optional second parameter for colors or the attrs parameter for bold (and other attributes such as underline) in addition to the normal named print arguments such as file or end.
import sys
from termcolor import cprint
cprint('Hello', 'green', attrs=['bold'], file=sys.stderr)
Full disclosure, this answer is heavily based on Olu Smith's answer
and was intended as an edit, which would have reduced the noise on this page
considerably but because of some reviewers' misguided concept of
what an edit is supposed to be, I am now forced to make this a separate answer.
Simple boldness - two-line code
In Pythonย 3, you could use Colorama - simple_colors:
(On the Simple Colours page*, go to the heading 'Usage'.) Before you do what is below. Make sure you pip install simple_colours.
from simple_colors import *
print(green('hello', 'bold'))
Some terminals allow to print colored text. Some colors look like if they are "bold". Try:
print ('\033[1;37mciao!')
The sequence '\033[1;37m' makes some terminals to start printing in "bright white" that may look a bit like bolded white. '\033[0;0m' will turn it off.
Assuming that you really mean "print" on a real printing terminal:
>>> text = 'foo bar\r\noof\trab\r\n'
>>> ''.join(s if i & 1 else (s + '\b' * len(s)) * 2 + s
... for i, s in enumerate(re.split(r'(\s+)', text)))
'foo\x08\x08\x08foo\x08\x08\x08foo bar\x08\x08\x08bar\x08\x08\x08bar\r\noof\x08\
x08\x08oof\x08\x08\x08oof\trab\x08\x08\x08rab\x08\x08\x08rab\r\n'
Just send that to your stdout.
A simple approach relies on Unicode Mathematical Alphanumeric Symbols.
Code
def bold(
text,
trans=str.maketrans(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"๐๐๐๐๐๐๐๐๐๐๐๐๐ ๐ก๐ข๐ฃ๐ค๐ฅ๐ฆ๐ง๐จ๐ฉ๐ช๐ซ๐ฌ๐ญ๐ฎ๐ฏ๐ฐ๐ฑ๐ฒ๐ณ๐ด๐ต๐ถ๐ท๐ธ๐น๐บ๐ป๐ผ๐ฝ๐พ๐ฟ๐๐๐๐๐๐
๐๐๐ฌ๐ญ๐ฎ๐ฏ๐ฐ๐ฑ๐ฒ๐ณ๐ด๐ต",
),
):
return text.translate(trans)
Example
assert bold("Hello world") == "๐๐ฒ๐น๐น๐ผ ๐๐ผ๐ฟ๐น๐ฑ"
Discussion
Several pros and cons I can think of. Feel free to add yours in the comments.
Advantages:
As short as readable.
No external library.
Portable: can be used for instance to highlight sections in an ipywidgets Dropdown.
Extensible to italics, etc. with the appropriate translation tables.
Language agnostic: the same technic can be implemented in any programming language.
Drawbacks:
Requires Unicode support and a font where all the required glyphs are defined. This should be ok on any reasonably modern system, though.
No copy-pasteย : produces a faux-text. Note that '๐๐ผ๐ฟ๐น๐ฑ'.isalpha() is still True, though.
No diacritics.
Implementation notes
In the code above, the translation table is given as an optional argument, meaning that it is evaluated only once, and conveniently encapsulated in the function which makes use it. If you prefer a more standard style, define a global BOLD_TRANS constant, or use a closure or a lightweight class.
The bold text goes like this in Python:
print("This is how the {}bold{} text looks like in Python".format('\033[1m', '\033[0m'))
This is how the bold text looks like in Python.
Printing in bold made easy.
Install quo using pip:
from quo import echo
echo(f"Hello, World!", bold=True)
There is something called escape sequence which is used to represent characters that is not available in your keyboard. It can be used for formatting text (in this case bold letter format), represent special character with specific ASCII code and to represent Unicode characters.
In Python, escape sequences are denoted by a backslash \ followed by one or more characters. For example, the escape sequence \n represents a newline character, and the escape sequence \t represents a tab character.
Here for formatting text in bold use \033[1m before and after the text you want to represent in bold.
example-
print("This line represent example of \033[1mescape sequence\033[0m.")
In the escape sequence \033[1m, the 1 enables bold text, while the m is the command to set the text formatting. The \033[0m escape sequence resets the text formatting to the default settings.
The \033[0m escape sequence is used after the \033[1m escape sequence to turn off bold text and return to the default text formatting. This is necessary because the \033[1m escape sequence only enables bold text, it does not disable it.
def say(text: str):
print ("\033[1;37m" + text)
say("Hello, world!")
my code works okay.
Related
Is the usage of escaped characters such as \t allowed by PEP8 in something like print statements?
Is there a more idiomatic way to left indent some of the printout without importing non standard libraries?
Yeah that's fine, it is a fundamental ASCII character - PEP would not deny its use as it may be fundamental to your end result (say an API needed tabs or something) - PEP is all about styling your source code, I wouldn't consider a character in a string to be something that can be decreed by a style guide (PEP8).
Though there is nothing wrong with using \t, you might want to use the textwrap module to allow your indented text to be displayed more naturally in your source code. As an alternative to msg = '\teggs\tmilk\tbread', you can write
import textwrap
def show_list():
msg = """\
eggs
milk
bread"""
print(textwrap.indent(textwrap.dedent(msg), "\t"))
Then show_list() produces the output
eggs
milk
bread
When you indent the definition of msg, the whitespace is part of the literal. dedent removes the common leading whitespace from each line of the string. The indent method then indents each line with, specifically, a tab character.
There is nothing wrong using the tabulator character in a string, at all. See e.g. the Wikipedia link for some common usages. You may be confused by this PEP-8 info:
Use 4 spaces per indentation level.
This is similar to Joe Iddon's answer. It has to be clear that writing a text (not code, of course) is something different than writing code. Texts and their usages are very inhomogeneous. So setting rules how to format your text does not make any sense (if text is not code).
But you also asked "Is there a more idiomatic way to left indent some of the printout without importing non standard libraries?"
Since Python3.6 You can use formatted string literals to get additional spaces (indentation) in your strings you want to print. (If you're using Python3.5 and lower, you can use the str.format instead, for example.)
The usage is like this:
>>> text = "Hello World"
>>> print(f"\t{text}")
Hello World
This is just a toy example, of course. F-Strings become more useful with more complex strings. If you don't have such complex strings, you can consider also using the arguments of print() statement like this, for example:
>>> print("Foo", "Bar", "Foo", "Bar", sep="\t\t") # doubled "\t" only for better displaying
Foo Bar Foo Bar
But often it is simply quite enough to include the tab character in your string, e.g.: "Hello World!\tHow are you doing?\tThat's it.". As already said, don't do that with code (PEP-8), but in texts it is fine.
If you want to use a module for that (it is a built-in module), I recommend using textwrap. See chepner's answer for more information how to use that.
I am very new to Python, and wanted to learn how to print coloured text. I don't have any modules like termcolor or colorama, but I found that I can use ANSI escape sequences to do this.
I found a sample code:
print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')
However, when I run it, it just prints the entire thing like this:
[6;30;42mSuccess![0m
What am I doing wrong, and how can I print coloured texts?
Thank you very much!!
Edit: I am using python 3.7
So it turned out you were doing nothing wrong, just executing the Python code in an environment (the IDLE IDE on Mac) which does not recognize (by default?) ANSI escape sequences.
On Mac, ANSI escape sequences are supported, e.g., by Terminal.
Try this
Blue = '\033[34m' # Blue Text
print(Blue + 'Hello World')
at the spot where it says 34m that is the colour. red is 31
yellow is 33 purple is 35. and more. THis works for python
The question is straightforward, is it possible to change the font family of text in a Python print() output? Like Times New Roman, Arial, or Comic Sans?
I only want to change some of the output. Not all of the text like in this question.
I'm using Python 3 and Jupyter Notebook on a Mac.
I know it's possible to make certain text bold like so:
bold_start = '\033[1m'
bold_end = '\033[0m'
print(bold_start, "Hello", bold_end, "World")
This outputs "Hello World" instead of "Hello World" or "Hello World"
Python strings are just strings of Unicode characters, they don't say anything about font one way or another. The font is determined by whatever is rendering the characters, e.g. the terminal program you're using, or the browser you're using. The print function just spits out the resulting string.
As you pointed out, if you're in a terminal that understands those escape sequences, then you can use those to affect the output. If your output is a web page, then you can embed html code to specify whatever you like, but all the python interpreter sees is a string of characters, not a string of characters in any particular font.
How to highlight a word/letter in a text by changing its color\colour using python 2.7?
try:
using clint.
>>> from clint.textui import puts, colored
>>> puts(colored.red('Text in Red'))
Text in Red
but i want to color only the 'x' in the 'Text' for example.
import termcolor
string = 'Text in Red'
string = string.replace('x', termcolor.colored('x', 'red'))
print string
The following will work.
>>> from clint.textui import puts, colored
>>> puts('Te'+colored.red('x')+'t in Red')
Let me explain why this works by first explaining how colors are displayed in the console.
When you want to tell the console to change colors you would think you would have to do some special system call or something, but all you have to do is output some special characters called an ansi escape sequence. Clint handles this for you. When you used the clint.ansi.red function, the escape character for red was added before the x and the escape character to reset everything back to normal was added after the x.
This means that, 'Te'+colored.red('x')+'t in Red' is the same thing as 'Te\x1b[31m\x1b[22mx\x1b[39m\x1b[22mt in Red', and you can continue to add text in others colors to your hearts content.
Also, clint handles this, but just for informational purposes, if you want to see the full list of color escape sequences they can be found here. There are other ansi codes that allow you to do things like changing the position of the cursor. You can find a list of all of the ansi codes here. If you mess with ansi codes outside of the clint library, make sure you're taking into account every flow of control including unexpected exceptions that need will need to revert the text back to normal. It's no fun to execute a program, run into some errors that turn the console red, and then have the program exit, but you're still left with a red console.
Here's a non-external library approach which I tend to use a lot
class bcolors:
RED = '\033[91m'
GREEN = '\033[92m'
BLUE = '\033[94m'
CYAN = '\033[96m'
WHITE = '\033[97m'
YELLOW = '\033[93m'
MAGENTA = '\033[95m'
GREY = '\033[90m'
BLACK = '\033[90m'
DEFAULT = '\033[99m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
print(bcolors.WHITE + foo + bcolors.END)
print(bcolors.GREEN + bar + bcolors.END)
I'm writing a little python utility to help move our shell -help documentation to searchable webpages, but I hit a weird block :
output = subprocess.Popen([sys.argv[1], '--help'],stdout=subprocess.PIPE).communicate()[0]
output = output.split('\n')
print output[4]
#NAME
for l in output[4]:
print l
#N
#A
#
#A
#M
#
#M
#E
#
#E
#or when written, n?na?am?me?e
It does this for any heading/subheading in the documentation, which makes it near unusable.
Any tips on getting correct formatting? Where did I screw up?
Thanks
The documentation contains overstruck characters done in the ancient line-printer way: print each character, followed by a backspace (\b aka \x08), followed by the same character again. So "NAME" becomes "N\bNA\bAM\bME\bE". If you can convince the program not to output that way, it would be the best; otherwise, you can clean it up with something like output = re.sub(r'\x08.', '', output)
A common way to mark a character as bold in a terminal is to print the character, followed by a backspace characters, followed by the character itself again (just like you would do it on a mechanical typewriter). Terminal emulators like xterm detect such sequences and turn them into bold characters. Programs shouldn't be printing such sequences if stdout is not a terminal, but if your tool does, you will have to clean up the mess yourself.