Formatted text in Linux Terminal using Python

In this section, we will see how to print formatted texts in Linux terminal. By formatting, we can change the text color, style, and some special features using ANSI escape sequences.

Linux terminal supports ANSI escape sequences to control the formatting, color and other features. We embed these special bytes with the text, and when the terminal interprets them, the formatting becomes effective.

ANSI Escape Sequence Syntax

The general syntax of ANSI escape sequence is ?

\x1b[A;B;C

Where:

  • A is the Text Formatting Style
  • B is the Text Color or Foreground Color
  • C is the Background Color

Text Formatting Style Codes

The following values control text formatting styles ?

Values Style
1 Bold
2 Faint
3 Italic
4 Underline
5 Blinking
6 Fast Blinking
7 Reverse
8 Hide
9 Strikethrough

Color Codes

The color codes for foreground (B) and background (C) ?

Foreground (B) Background (C) Color
30 40 Black
31 41 Red
32 42 Green
33 43 Yellow
34 44 Blue
35 45 Magenta
36 46 Cyan
37 47 White

Terminal Formatter Class Example

Here's a complete Python class to handle terminal formatting ?

class Terminal_Format:
    Color_Code = {'black': 0, 'red': 1, 'green': 2, 'yellow': 3, 
                  'blue': 4, 'magenta': 5, 'cyan': 6, 'white': 7}
    Format_Code = {'bold': 1, 'faint': 2, 'italic': 3, 'underline': 4, 
                   'blinking': 5, 'fast_blinking': 6, 'reverse': 7, 
                   'hide': 8, 'strikethrough': 9}
    
    def __init__(self):  # reset the terminal styling at first
        self.reset_terminal()
    
    def reset_terminal(self):  # Reset the properties
        self.property = {'text_style': None, 'fg_color': None, 'bg_color': None}
        return self
    
    def config(self, style=None, fg_col=None, bg_col=None):  # Set all properties
        return self.reset_terminal().text_style(style).foreground(fg_col).background(bg_col)
    
    def text_style(self, style):  # Set the text style
        if style in self.Format_Code.keys():
            self.property['text_style'] = self.Format_Code[style]
        return self
    
    def foreground(self, fg_col):  # Set the Foreground Color
        if fg_col in self.Color_Code.keys():
            self.property['fg_color'] = 30 + self.Color_Code[fg_col]
        return self
    
    def background(self, bg_col):  # Set the Background Color
        if bg_col in self.Color_Code.keys():
            self.property['bg_color'] = 40 + self.Color_Code[bg_col]
        return self
    
    def format_terminal(self, string):
        temp = [self.property['text_style'], self.property['fg_color'], 
                self.property['bg_color']]
        temp = [str(x) for x in temp if x is not None]
        # return formatted string
        return '\x1b[%sm%s\x1b[0m' % (';'.join(temp), string) if temp else string
    
    def output(self, my_str):
        print(self.format_terminal(my_str))

# Example usage
formatter = Terminal_Format()

# Bold red text
formatter.config(style='bold', fg_col='red')
formatter.output("This is bold red text")

# Blue background with white text
formatter.config(fg_col='white', bg_col='blue')
formatter.output("White text on blue background")

# Underlined green text
formatter.config(style='underline', fg_col='green')
formatter.output("This is underlined green text")

Simple ANSI Examples

You can also use ANSI codes directly without the class ?

# Bold red text
print('\x1b[1;31mBold Red Text\x1b[0m')

# Blue background
print('\x1b[44mBlue Background\x1b[0m')

# Underlined text
print('\x1b[4mUnderlined Text\x1b[0m')

# Combination: Bold white text on red background
print('\x1b[1;37;41mBold White on Red\x1b[0m')

How It Works

The Terminal_Format class provides a convenient way to:

  • Chain methods: Configure multiple properties in sequence
  • Reset formatting: Clear all styles between different outputs
  • Apply combinations: Mix text styles, foreground and background colors
  • Output formatted text: Print with applied formatting automatically

The \x1b[0m sequence at the end resets all formatting to prevent it from affecting subsequent text.

Conclusion

ANSI escape sequences allow you to create colorful and styled terminal output in Python. Use the Terminal_Format class for complex formatting or direct ANSI codes for simple styling needs.

Updated on: 2026-03-25T05:07:05+05:30

408 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements