如何使用python使文本加粗

问题描述

我需要将字符串设为粗体。我用过:

from colorama import init,Fore,Back,Style

y='Hello world'

我想将加粗的“y”传递给另一个变量。

解决方法

我认为一般没有办法做到这一点。但是,使用 this answer here,您或许可以建立最适合您需要的 Bold 类。

import colorama

colorama.init()  # catch the format on windows to print correctly


class Format:
   PURPLE = '\033[95m'
   CYAN = '\033[96m'
   DARKCYAN = '\033[36m'
   BLUE = '\033[94m'
   GREEN = '\033[92m'
   YELLOW = '\033[93m'
   RED = '\033[91m'
   BOLD = '\033[1m'
   UNDERLINE = '\033[4m'
   END = '\033[0m'


class Bold(str):

    def __init__(self,t):
        self.t = t

    def asHTML(self):
        """Returns the text formated for HTML usaage"""
        return f"<b>{self.t}</b>"

    def asMD(self):
        """Returns the text formated for additions to markdown files,like for example a README.md"""
        return "**" + self.t + "**"

    def __str__(self):
        return Format.BOLD + self.t + Format.END


y = 'Hello world'
y = Bold(y)
print(y)
print(y.lower())  # not actually in bold ! 
# Do not forget to overwrite any function like this to 'reboldify' the text

这对我来说打印:

你好世界

你好世界

,

我强烈建议您查看 https://github.com/willmcgugan/rich :)

from rich import print

print("Hello,[bold magenta]World[/bold magenta]!")

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...