0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Python】出力文字に色を付ける

Posted at

何?

print()などで出力する文字に色を付ける。

class AnsiStyle:
    """ANSIカラーコードを提供するクラス"""

    BLACK = "\033[30m"
    RED = "\033[31m"
    GREEN = "\033[32m"
    YELLOW = "\033[33m"
    BLUE = "\033[34m"
    MAGENTA = "\033[35m"
    CYAN = "\033[36m"
    WHITE = "\033[37m"
    RESET = "\033[0m"

    BOLD = "\033[1m"
    UNDERLINE = "\033[4m"
    REVERSED = "\033[7m"

    @classmethod
    def get(cls, name: str, *, strict: bool = False) -> str:
        """色名を指定してカラーコードを取得する。

        strict=True の場合、存在しない色なら例外を発生させる

        Args:
            name (str): 色名
            strict (bool): 未知の色名の場合に例外を発生させるか

        Returns:
            str: カラーコード

        Raises:
            ValueError: strict=True で未知の色名が指定された場合

        """
        color = getattr(cls, name.upper(), None)
        if color is None:
            if strict:
                message = f"'{name}' は有効な色名ではありません。 有効な色名: {cls.available_colors()}"
                raise ValueError(message)
            return cls.RESET
        return color

    @classmethod
    def available_colors(cls) -> list:
        """利用可能な色名の一覧を取得する

        Returns:
            list: 利用可能な色名のリスト

        """
        return [attr for attr in dir(cls) if attr.isupper() and not attr.startswith("_")]

    @classmethod
    def format(cls, text: str, color: str, *,
               bold: bool = False,
               underline: bool = False,
               reversed_: bool = False,
               ) -> str:
        """テキストに色やスタイルを適用して返す

        Args:
            text (str): 対象のテキスト
            color (str): 色名
            bold (bool): 太字にするか
            underline (bool): 下線を引くか
            reversed_ (bool): 文字色と背景色を反転させるか

        Returns:
            str: スタイルが適用されたテキスト

        """
        style = cls.get(color, strict=True)
        if bold:
            style += cls.BOLD
        if underline:
            style += cls.UNDERLINE
        if reversed_:
            style += cls.REVERSED
        return f"{style}{text}{cls.RESET}"

使い方

cololize_text = AnsiStyle.format("Hello, World!", "red")
print(cololize_text)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?