简体   繁体   中英

How to center printed text with pyfiglet in Python

I would want to print on the center text that has been made with py-figlet ( https://github.com/pwaller/pyfiglet ).

My code looks like this:

from pyfiglet import Figlet

f = Figlet(font='ascii___')

def DrawText(text):
    return f.renderText(text)

print(DrawText('text')) <- Center it

On output I would want to have text printed on center with pyfiglet printing.

You can smartly use .center() with shutil module:

from pyfiglet import Figlet
import shutil

f = Figlet(font='ascii___')

def DrawText(text,center=True):
    if center:
      print(*[x.center(shutil.get_terminal_size().columns) for x in f.renderText(text).split("\n")],sep="\n")  
    else:
      print(f.renderText(text))

DrawText('text',center=True)

You can use the keyword justify with 'auto', 'left', 'center', or 'right'

I did this:

import pyfiglet

txt = "title"
banner = pyfiglet.figlet_format(txt, font="slant", justify="center")

print(banner)

I couldn't find a decent documentation of the module. So I had to dig through the code, and found the keywords for the FigletBuilder class constructor. It starts like this:

class FigletBuilder(object):
    """
    Represent the internals of the build process
    """
    def __init__(self, text, font, direction, width, justify):

        self.text = list(map(ord, list(text)))
        self.direction = direction
        self.width = width
        self.font = font
        self.justify = justify

the OptionParser in the main() function (currently line 865) , also gives an indication on how to use the keywords, just in case you want to learn more about how to use the keyword arguments, but don't want to scroll through about 1000 lines of code ^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM