Cara menggunakan python alignment format

Text formating pada python akan membahas formating print out pada console. Lesson ini bertujuan untuk mengenalkan formating sederhana. Formating ini bermanfaat untuk memudahkan kita dalam membaca hasil print out.

Formating Teks

Untuk memudahkan, kita gunakan perintah print agar bisa melihat langsung hasil dari string formating. Untuk versi Python sebelum 3.6, harus menggunakan perintah format untuk melakukan string formating.

nama = 'Brad'

#sebelum python 3.6
print("My name is {}".format(nama))

#python 3.6
print(f"My name is {nama}")
#My name is Brad

Pada Python 3.6 keatas, kita dapat menggunakan f-string literal untuk melakukan formating. Code menjadi lebih clean dan mudah dibaca.

Ini juga berlaku untuk type data lainnya seperti dictionary atau list.

d = {'a': 123, 'b': 456}
l = [0, 1, 2]

print(f"My dict number is {d['a']}")
#My number is 123

print(f"My list number is {l[0]}")
#My list number is 0

Menambahkan Padding

Selain mempercantik hasil print, menambahkan padding juga memudahkan dalam membaca hasil print ke console. Hal ini dibahas karena, hasil print out dari library spaCy kurang nyaman untuk dibaca.

buku = [('Author', 'Topic', 'Pages'), ('Dalai Lama', 'Pefecting Patience', 201), ('Catherine Blyth', 'The art of Conversation', 90), ('Mike Leibling', 'How People Tick', 122)]

for author, topic, pages in buku:
    print(f"{author} {topic} {pages}")

#Author Topic Pages
#Dalai Lama Pefecting Patience 201
#Catherine Blyth The art of Conversation 90
#Mike Leibling How People Tick 122

for author, topic, pages in buku:
    print(f"{author:{15}} {topic:{25}} {pages:>{10}}")

#Author          Topic                          Pages
#Dalai Lama      Pefecting Patience               201
#Catherine Blyth The art of Conversation           90
#Mike Leibling   How People Tick                  122

Program diatas memiliki variable buku yang merupakan list of tuple. Kemudian mencetak isi dari variable buku dengan menambahkan padding.

Padding dilakukan dengan menambahkan tanda : (colon) dan angka untuk menentukan minimum width dari kolom tersebut.

Karena pages adalah kombinasi dari string dan integer. Cara termudah adalah menggunakan tanda > (lebih besar) agar string dan integer akan di align rata kanan.

 print(f"{author:15} {topic:25} {pages:>10}")

Kita juga bisa menambahkan karakter lain seperti . (titik) diantara : dan >.

for author, topic, pages in buku:
    print(f"{author:{15}} {topic:{25}} {pages:.>{10}}")

#Author          Topic                     .....Pages
#Dalai Lama      Pefecting Patience        .......201
#Catherine Blyth The art of Conversation   ........90
#Mike Leibling   How People Tick           .......122

DateTime Formating

DateTime formating menggunakan strf time code, dapat dilihat di strftime.org

from datetime import datetime

today = datetime(year=2019, month=9, day=18)

print(f"{today}")
#2019-09-18 00:00:00

print(f"{today: %d-%m-%Y}")
#18-09-2019
  • %d : tanggal dengan nol didepan.
  • %m: bulan dengan nol didepan.
  • %Y: tahun 4 digit.

Lesson ini hanya menunjukan formating sederhana saja. Silakan berekperimen dengan formating yang lebih rumit.

Rich is a Python library for writing rich text (with color and style) to the terminal. It lets you display advanced content such as tables, markdown, and syntax-highlighted code.

So, why is this useful? Well, if you're not using a tool like Rich, the output of your code on the terminal can be a little boring and difficult to understand. If you want to make it clearer and prettier, you probably want to use Rich – and you've come to the right place to learn how to do it.

How to Install Rich

You can install Rich with pip as:

pip install Rich

To know what all Rich can do, you can type the following command in the terminal:

python -m rich
Cara menggunakan python alignment format

Now you can see that we can do quite a lot of things with Rich. Let's try a few of them out to see how they work.

How to Rich print in Python

Rich has the capability to highlight the output according to the datatype. We'll import the alternative

python -m rich
2 function from the Rich library which takes the same arguments as the built-in
python -m rich
2.

To avoid confusion with the built-in

python -m rich
2 function, we'll import
python -m rich
2 from the
python -m rich
6 library as
python -m rich
7.

from rich import print as rprint

nums_list = [1, 2, 3, 4]
rprint(nums_list)

nums_tuple = (1, 2, 3, 4)
rprint(nums_tuple)

nums_dict = {'nums_list': nums_list, 'nums_tuple': nums_tuple}
rprint(nums_dict)

bool_list = [True, False]
rprint(bool_list)

Output:

Cara menggunakan python alignment format

Do you see how the different data types are highlighted with different colors? This can help us a lot while debugging.

How to Rich inspect in Python

If you use the built-in

python -m rich
8 function for viewing the documentation of a library, you'll see a boring output.

import rich

print(help(rich))

Output:

Cara menggunakan python alignment format

Rich has an function which can generate a report on any Python object. It is a fantastic debug aid, and a good example of the output that Rich can generate.

from rich import inspect
import rich

inspect(rich)

Output:

Cara menggunakan python alignment format

How to style your console with Rich

For complete control over terminal formatting, Rich offers a class.

Let's write a function to merge Python dictionaries.

from rich.console import Console

console = Console()


def merge_dict(dict_one, dict_two):
    merged_dict = dict_one | dict_two
    console.log(merged_dict, log_locals=True)


merge_dict({'id': 1}, {'name': 'Ashutosh'})

Output:

Cara menggunakan python alignment format

In the above example, we have used the

from rich import print as rprint

nums_list = [1, 2, 3, 4]
rprint(nums_list)

nums_tuple = (1, 2, 3, 4)
rprint(nums_tuple)

nums_dict = {'nums_list': nums_list, 'nums_tuple': nums_tuple}
rprint(nums_dict)

bool_list = [True, False]
rprint(bool_list)
1 method that offers the same capabilities as print, but adds some features useful for debugging a running application.

There are several other methods such as

from rich import print as rprint

nums_list = [1, 2, 3, 4]
rprint(nums_list)

nums_tuple = (1, 2, 3, 4)
rprint(nums_tuple)

nums_dict = {'nums_list': nums_list, 'nums_tuple': nums_tuple}
rprint(nums_dict)

bool_list = [True, False]
rprint(bool_list)
2,
from rich import print as rprint

nums_list = [1, 2, 3, 4]
rprint(nums_list)

nums_tuple = (1, 2, 3, 4)
rprint(nums_tuple)

nums_dict = {'nums_list': nums_list, 'nums_tuple': nums_tuple}
rprint(nums_dict)

bool_list = [True, False]
rprint(bool_list)
3,
from rich import print as rprint

nums_list = [1, 2, 3, 4]
rprint(nums_list)

nums_tuple = (1, 2, 3, 4)
rprint(nums_tuple)

nums_dict = {'nums_list': nums_list, 'nums_tuple': nums_tuple}
rprint(nums_dict)

bool_list = [True, False]
rprint(bool_list)
4,
from rich import print as rprint

nums_list = [1, 2, 3, 4]
rprint(nums_list)

nums_tuple = (1, 2, 3, 4)
rprint(nums_tuple)

nums_dict = {'nums_list': nums_list, 'nums_tuple': nums_tuple}
rprint(nums_dict)

bool_list = [True, False]
rprint(bool_list)
5, and so on. Learn more about them here.

How to use Tree in Rich

Rich has a class which can generate a tree view in the terminal. A tree view is a great way of presenting the contents of a filesystem or any other hierarchical data. Each branch of the tree can have a label which may be text or any other Rich renderable.

Let's see an example by creating a family tree:

from rich.tree import Tree
from rich import print as rprint


tree = Tree("Family Tree")
tree.add("Mom")
tree.add("Dad")
tree.add("Brother").add("Wife")
tree.add("[red]Sister").add("[green]Husband").add("[blue]Son")

rprint(tree)

Output:

Cara menggunakan python alignment format

Once we create an instance of the

from rich import print as rprint

nums_list = [1, 2, 3, 4]
rprint(nums_list)

nums_tuple = (1, 2, 3, 4)
rprint(nums_tuple)

nums_dict = {'nums_list': nums_list, 'nums_tuple': nums_tuple}
rprint(nums_dict)

bool_list = [True, False]
rprint(bool_list)
6 class, we can use the
from rich import print as rprint

nums_list = [1, 2, 3, 4]
rprint(nums_list)

nums_tuple = (1, 2, 3, 4)
rprint(nums_tuple)

nums_dict = {'nums_list': nums_list, 'nums_tuple': nums_tuple}
rprint(nums_dict)

bool_list = [True, False]
rprint(bool_list)
8 method to add branches to it. To create a complex tree, you just use the
from rich import print as rprint

nums_list = [1, 2, 3, 4]
rprint(nums_list)

nums_tuple = (1, 2, 3, 4)
rprint(nums_tuple)

nums_dict = {'nums_list': nums_list, 'nums_tuple': nums_tuple}
rprint(nums_dict)

bool_list = [True, False]
rprint(bool_list)
8 method to add more branches to it. Notice the Brother and Sister branch in the above example.

In the official documentation, we have a tree.py file that outputs the file structure using Tree. The output looks like this:

Cara menggunakan python alignment format

How to display a progress bar using Rich

Rich can show continuously updated information about the status of long-running tasks, file copies, and so forth. You can customize this information, too. By default, it provides a description of the 'task,' a progress bar, percentage complete, and anticipated time left.

Multiple tasks are supported with a rich progress display, each with a bar and progress statistics. You can use this to keep track of several jobs that are being worked on in threads or processes.

Let's first try the

import rich

print(help(rich))
0 method to create the progress bar.

from rich.progress import track
from time import sleep


def process_data():
    sleep(0.02)


for _ in track(range(100), description='[green]Processing data'):
    process_data()

Output:

Cara menggunakan python alignment format

If we want to record the time when a particular task is finished executing, we can use

import rich

print(help(rich))
1 instead.

from rich.console import Console
from time import sleep

console = Console()

data = [1, 2, 3, 4, 5]
with console.status("[bold green]Fetching data...") as status:
    while data:
        num = data.pop(0)
        sleep(1)
        console.log(f"[green]Finish fetching data[/green] {num}")

    console.log(f'[bold][red]Done!')
Cara menggunakan python alignment format

You can work directly with the Progress class if you need several tasks in the display or want to customize the columns in the progress display. After you've created a Progress object, use (

import rich

print(help(rich))
2) to add task(s) and (
import rich

print(help(rich))
3) to update progress.

The Progress class is intended to be used as a context manager, automatically starting and stopping the progress display.

import time

from rich.progress import Progress

with Progress() as progress:

    task1 = progress.add_task("[red]Downloading...", total=100)
    task2 = progress.add_task("[green]Processing...", total=100)
    task3 = progress.add_task("[cyan]Installing...", total=100)

    while not progress.finished:
        progress.update(task1, advance=0.9)
        progress.update(task2, advance=0.6)
        progress.update(task3, advance=0.3)
        time.sleep(0.02)

Output:

Cara menggunakan python alignment format

How to display Rich Columns in Python

Rich can render text or other Rich renderables in neat columns with the class. To use, construct a Columns instance with an iterable of renderables and print it to the Console.

python -m rich
0

Output:

Cara menggunakan python alignment format

How to display Rich tables in Python

Rich’s class offers a variety of ways to render tabular data to the terminal. This class has

import rich

print(help(rich))
6 and
import rich

print(help(rich))
7 methods to add column and row respectively to the table instance created from the
import rich

print(help(rich))
5 class.

Let's create a table for our todo list. This table will have three columns – S.No., Task, and Status.

python -m rich
1

Output:

Cara menggunakan python alignment format

Wrapping Up

In this tutorial, we learned how to use Rich to beautify the terminal. There are lots of other features that Rich supports. Learn more about them in the official documentation.

Feel free to fork and play with the source code of this article here.

Thanks for reading!

Subscribe to my newsletter

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT


Cara menggunakan python alignment format
Ashutosh Krishna

Application Developer at Thoughtworks India


If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Apa fungsi format pada python?

Fungsi format() berfungsi untuk melakukan pengaturan format string yang akan dicetak atau ditampilkan ke monitor. Contoh syntax : format(value[, format_spec])

Apa itu string format?

String Formatting atau Pemformatan string memungkinkan kita menyuntikkan item ke dalam string daripada kita mencoba menggabungkan string menggunakan koma atau string concatenation. Sebagai gambaran, perbandingannya seperti ini : Nama = 'Budi' Umur = 25 'Nama saya '+Nama+', umur saya sekarang '+str(Umur)+' Tahun. '