简体   繁体   English

如何在 Python 中使用 pyfiglet 将打印文本居中

[英]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 ).我想在用 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.在输出时,我希望使用 pyfiglet 打印在中心打印文本。

You can smartly use .center() with shutil module:您可以巧妙地将.center()shutil模块一起使用:

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'您可以将关键字justify“auto”、“left”、“center”“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.所以我不得不深入研究代码,找到 FigletBuilder 类构造函数的关键字。 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 ^^ main()函数(当前第 865 行)中OptionParser还给出了如何使用关键字的指示,以防万一您想了解有关如何使用关键字参数的更多信息,但不想滚动浏览1000行代码^^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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