Skip to main content

ANSI String Formatter in Python for CLI Color and Style Formatting

Project description

ansi-string

ANSI String Formatter in Python for CLI Color and Style Formatting

Introduction

This code was originally written for greplica, but I felt it deserved its own, separate library.

The main goals for this project are:

  • To provide a simple way to construct a string-like object with embedded ANSI formatting without requiring the developer to know how ANSI formatting works
  • Provide a way to further format the object using format string
  • Allow for concatenation of the object

Contribution

Feel free to open a bug report or make a merge request on github.

Installation

This project is uploaded to PyPI at https://pypi.org/project/ansi-string

To install, ensure you are connected to the internet and execute: python3 -m pip install ansi-string --upgrade

Examples

Examples

Refer to the test file for more examples on how to use the AnsiString class.

Usage

To begin, import AnsiString from the ansi_string module.

from ansi_string import en_tty_ansi, AnsiFormat, AnsiString

Enabling ANSI Formatting

Windows requires ANSI formatting to be enabled before it can be used. This can either be set in the environment or by simply calling the following before printing so that ANSI is enabled locally.

en_tty_ansi()

If this also needs to be enabled for stderr, stderr may also be passed to this method.

import sys
en_tty_ansi(sys.stderr)

For Windows, this returns True if the given IO is a TTY (i.e. not piped to a file) and enabling ANSI was successful. For all other operating systems, this will return True if and only if the given IO is a TTY (i.e. isatty()); no other action is taken.

Construction

The AnsiString class contains the following __init__ method.

class AnsiString:
    def __init__(self, s:str='', *setting_or_settings:Union[List[str], str, List[int], int, List[AnsiFormat], AnsiFormat]): ...

The first argument, s, is a string to be formatted. The next 0 to N arguments are formatting setting directives that can be applied to the entire string. These arguments can be in the form of any of the following.

  • An AnsiFormat enum (ex: AnsiFormat.BOLD)
  • The result of calling AnsiFormat.rgb(), AnsiFormat.fg_rgb(), AnsiFormat.bg_rgb(), AnsiFormat.ul_rgb(), or AnsiFormat.dul_rgb()
  • A string color or formatting name (i.e. any name of the AnsiFormat enum in lower or upper case)
  • An rgb(...) function directive as a string (ex: "rgb(255, 255, 255)")
    • rgb(...) or fg_rgb(...) to adjust text color
    • bg_rgb(...) to adjust background color
    • ul_rgb(...) to enable underline and set the underline color
    • dul_rgb(...) to enable double underline and set the underline color
    • Value given may be either a 24-bit integer or 3 x 8-bit integers, separated by commas
    • Each given value within the parenthesis is treated as hexadecimal if the value starts with "0x", otherwise it is treated as a decimal value

A formatting setting may also be any of the following, but it's not advised to specify settings in any of these ways unless there is a specific reason to do so.

  • An AnsiSetting object
  • A string containing known ANSI directives (ex: "01;31" for BOLD and FG_RED)
    • The string will normally be parsed into separate settings unless the character "[" is the first character of the string (ex: "[38;5;214")
    • Never specify the reset directive (0) because this is implicitly handled internally
  • A single ANSI directive as an integer

Examples:

# Set foreground to light_sea_green using string directive
# Set background to chocolate using AnsiFormat directive
# Underline in gray using ul_rgb() directive
# Enable italics using explicit string directive ("3")
# Enable bold using explicit integer directive (1)
s = AnsiString("This is an ANSI string", "light_sea_green", AnsiFormat.BG_CHOCOLATE, "ul_rgb(0x808080)", "3", 1)
print(s)

Concatenation

  • The static method AnsiString.join() is provided to join together 0 to many str and AnsiString values into a single AnsiString.
  • The + operator may be used to join an AnsiString with another AnsiString or str into a new AnsiString
    • The + operator may not be used if the left-hand-side value is a str and the right-hand-side values is an AnsiString
  • The += operator may be used to append an AnsiString or str to an AnsiString

Examples:

s = AnsiString.join("This ", AnsiString("string", AnsiFormat.BOLD))
s += AnsiString(" contains ") + AnsiString("multiple", AnsiFormat.BG_BLUE)
s += AnsiString(" color ", AnsiFormat.FG_ORANGE, AnsiFormat.ITALIC) + "settings accross different ranges"
print(s)

Formatting

apply_formatting

The method AnsiString.apply_formatting() is provided to append formatting to a previously constructed AnsiString.

Example:

s = AnsiString("This string contains multiple color settings across different ranges")
s.apply_formatting(AnsiFormat.BOLD, 5, 11)
s.apply_formatting(AnsiFormat.BG_BLUE, 21, 29)
s.apply_formatting([AnsiFormat.FG_ORANGE, AnsiFormat.ITALIC], 21, 35)
print(s)

Format String

A format string may be used to format an AnsiString before printing. The format specification string must be in the format "[string_format][:ansi_format]" where string_format is the standard string format specifier and ansi_format contains 0 or more ANSI directives separated by semicolons (;). The ANSI directives may be any of the same string values that can be passed to the AnsiString constructor. If no string_format is desired, then it can be set to an empty string.

Examples:

ansi_str = AnsiString("This is an ANSI string")
# Right justify with width of 100, formatted bold and red
print("{:>100:bold;red}".format(ansi_str))
# No justification settings, formatted bold and red
print("{::bold;red}".format(ansi_str))
# No justification settings, formatted bold and red
print("{::bold;rgb(255, 0, 0)}".format(ansi_str))
# No justification settings, formatted bold and red
print(f"{ansi_str::bold;red}")
# Format text, background, and underline with custom colors
fg_color = 0x8A2BE2
bg_colors = [100, 232, 170]
ul_colors = [0xFF, 0x63, 0x47]
print(f"{ansi_str::rgb({fg_color});bg_rgb({bg_colors});ul_rgb({ul_colors})}")

format_matching and unformat_matching

The method AnsiString.format_matching() and AnsiString.unformat_matching() are provided to apply or remove formatting of an AnsiString based on a match specification.

Example:

s = AnsiString("Here is a strING that I will match formatting", AnsiFormat.BOLD)
# This will make the word "formatting" cyan with a pink background
s.format_matching("[A-Za-z]+ing", "cyan", AnsiFormat.BG_PINK, regex=True, match_case=True)
# This will remove BOLD from "strING" and "formatting"
s.unformat_matching("[A-Za-z]+ing", AnsiFormat.BOLD, regex=True)
print(s)

clear_formatting

Calling the method AnsiString.clear_formatting() will clear all formatting applied.

String Assignment

The method AnsiString.assign_str() may be used to assign the internal string and adjust formatting as necessary.

Base String Retrieval

The attribute AnsiString.base_str may be used to retrieve the unformatted base string.

Format Status

The methods AnsiString.ansi_settings_at() and AnsiString.settings_at() may be used to retrieve the settings applied over a single character.

Other String Methods

Many other methods that are found in the str class such as replace() are available in AnsiString which manipulate the string while applying formatting where necessary.

  • capitalize
  • casefold
  • center
  • count
  • encode
  • endswith
  • expandtabs
  • find
  • index
  • isalnum
  • isalpha
  • isascii
  • isdecimal
  • isdigit
  • isidentifier
  • islower
  • isnumeric
  • isprintable
  • isspace
  • istitle
  • isupper
  • ljust
  • lower
  • lstrip
  • partition
  • removeprefix
  • removesuffix
  • replace
  • rfind
  • rindex
  • rjust
  • rpartition
  • rsplit
  • rstrip
  • split
  • splitlines
  • strip
  • swapcase
  • title
  • upper
  • zfill

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ansi-string-1.0.8.tar.gz (35.4 kB view details)

Uploaded Source

Built Distribution

ansi_string-1.0.8-py3-none-any.whl (32.0 kB view details)

Uploaded Python 3

File details

Details for the file ansi-string-1.0.8.tar.gz.

File metadata

  • Download URL: ansi-string-1.0.8.tar.gz
  • Upload date:
  • Size: 35.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for ansi-string-1.0.8.tar.gz
Algorithm Hash digest
SHA256 1793766770435cc900ddff27c39f24e8dcb8666c27f2d3b95f9abb17f7103839
MD5 c3a9c62f6d0f940fc4fb8b4d1c7a6222
BLAKE2b-256 b71201073adc0c0586767172119e3223eddcec12cee4de14eb8f13f6495689e1

See more details on using hashes here.

Provenance

The following attestation bundles were made for ansi-string-1.0.8.tar.gz:

Publisher: workflow.yml on Tails86/ansi-string

Attestations:

File details

Details for the file ansi_string-1.0.8-py3-none-any.whl.

File metadata

  • Download URL: ansi_string-1.0.8-py3-none-any.whl
  • Upload date:
  • Size: 32.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for ansi_string-1.0.8-py3-none-any.whl
Algorithm Hash digest
SHA256 8c5e62ec58e6657c34cee90878c473226b21374b59269719ecc274cb26066ca3
MD5 14f4479caaa49bc865f7667b1746f9f5
BLAKE2b-256 81ad43bdafe927e352ba0bada3b93f33e4a93117cc757818ca06e4203823582d

See more details on using hashes here.

Provenance

The following attestation bundles were made for ansi_string-1.0.8-py3-none-any.whl:

Publisher: workflow.yml on Tails86/ansi-string

Attestations:

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page