Formatted text in Linux Terminal using in Python

In this tutorial, we are going to discuss how to write formatted text in the Linux terminal using Python.

In general, we used plain text which doesn’t support various styling features, but the contrast to that there is another text type which is known as formatted text in general. It is also known as styled text or rich text which is the exact opposite of the plain text.

The formatted text provides us various information like:

  • Background color,text color
  • styling of the text(BOLD or ITALIC).
  • Hyperlink
  • Underlined Text
  • Strikethrough Text

There should be some specification which can control the features of the text. In the Linux terminal, ANSI Escape Codes are used to monitor the features of the text.

We can create a class for our convenience so that we can specify our styling format.

Code to Create a class for styling format

class Tformat:

    ClrCode = {
        'k': 0,  # black
        'r': 1,  # red
        'g': 2,  # green
        'y': 3,  # yellow
        'b': 4,  # blue
        'm': 5,  # magenta
        'c': 6,  # cyan
        'w': 7   # white
    }

    FmtCode = {
        'b': 1,  # bold
        'f': 2,  # faint
        'i': 3,  # italic
        'u': 4,  # underline
        'x': 5,  # blinking
        'y': 6,  # fast blinking
        'r': 7,  # reverse
        'h': 8,  # hide
        's': 9,  # strikethrough
    }
    def __init__(self):
        self.reset()

    def Reset(s):
        s.prop = { 'st': None, 'fg': None, 'bg': None }
        return s
    
    def configure(self, fg, bg=None, st=None):
        # reset and set all properties
        return self.reset().st(st).fg(fg).bg(bg)

    # set text style
    def Styletext(self, st):
        if st in self.Fmtcode.keys(): 
            self.prop['st'] = self.Fmtcode[st]
        return self

    def foreground(self, fg):
        if fg in self.Clrcode.keys():
            self.prop['fg'] = 30 + self.Clrcode[fg]
        return self

    def BackGround(self,bg):
        if bg in self.Clrcode.keys():
            self.prop['bg'] = 40 + self.Clrcode[bg]
        return self
    
    def format(self, string):
        wp = [self.prop['st'],self.prop['fg'], self.prop['bg']]
        wp = [ str(x) for x in wp if x is not None ]
        return '\x1b[%sm%s\x1b[0m' % (';'.join(wp), string) if w else string

    # output formatted string
    def out(self, string):
        print(self.format(string))

Save the above script as Textformat.py then to run it through terminal follow the following steps:

  • Import Tformat class from Textformat.
   from Textformat import Tformat.
  • Create an object of Tformat class.
   x=Tformat()
  • Configure the text using x.configure() method.
   x.configure('y', 'g', 'b')
  • Now print statement of your choice.
   x.out("We have done it!!")

You can also be referred to:

Leave a Reply

Your email address will not be published.