Skip to content

Formatters API

The formatters module provides utilities for formatting messages, handling text processing, creating interactive elements like buttons, and managing URLs. These utilities help create well-formatted responses across different channels.

Text Formatting

Utilities for processing and formatting text content.

Text formatting utilities.

Functions

remove_html_tags

remove_html_tags(text: str) -> str

Remove HTML tags from text.

Parameters:

Name Type Description Default
text str

Text containing HTML tags

required

Returns:

Type Description
str

Clean text with HTML tags removed

Source code in lex_helper/formatters/text.py
def remove_html_tags(text: str) -> str:
    """Remove HTML tags from text.

    Args:
        text: Text containing HTML tags

    Returns:
        Clean text with HTML tags removed
    """
    clean = re.compile("<.*?>")
    return re.sub(clean, "", text)

replace_special_characters

replace_special_characters(text: str, replacement: str | None = None) -> str

Replace special characters in text.

Parameters:

Name Type Description Default
text str

Text containing special characters

required
replacement str | None

Character to use as replacement (defaults to empty string)

None

Returns:

Type Description
str

Text with special characters replaced

Source code in lex_helper/formatters/text.py
def replace_special_characters(text: str, replacement: str | None = None) -> str:
    """Replace special characters in text.

    Args:
        text: Text containing special characters
        replacement: Character to use as replacement (defaults to empty string)

    Returns:
        Text with special characters replaced
    """
    if replacement is None:
        replacement = ""
    return re.sub(r"[^a-zA-Z0-9\s]", replacement, text)

substitute_keys_in_text

substitute_keys_in_text(text: str, substitutions: dict[str, str]) -> str

Substitute keys in text with their values.

Parameters:

Name Type Description Default
text str

Text containing keys to substitute

required
substitutions dict[str, str]

Dictionary of key-value pairs for substitution

required

Returns:

Type Description
str

Text with keys replaced by their values

Example

text = "Hello {name}!" subs = {"name": "World"} substitute_keys_in_text(text, subs) 'Hello World!'

Source code in lex_helper/formatters/text.py
def substitute_keys_in_text(text: str, substitutions: dict[str, str]) -> str:
    """Substitute keys in text with their values.

    Args:
        text: Text containing keys to substitute
        substitutions: Dictionary of key-value pairs for substitution

    Returns:
        Text with keys replaced by their values

    Example:
        >>> text = "Hello {name}!"
        >>> subs = {"name": "World"}
        >>> substitute_keys_in_text(text, subs)
        'Hello World!'
    """
    result = text
    for key, value in substitutions.items():
        pattern = r"\{" + re.escape(key) + r"\}"
        result = re.sub(pattern, str(value), result)
    return result

truncate_text

truncate_text(text: str, max_length: int, suffix: str = '...') -> str

Truncate text to specified length.

Parameters:

Name Type Description Default
text str

Text to truncate

required
max_length int

Maximum length of resulting text (including suffix)

required
suffix str

String to append to truncated text

'...'

Returns:

Type Description
str

Truncated text with suffix if needed

Source code in lex_helper/formatters/text.py
def truncate_text(text: str, max_length: int, suffix: str = "...") -> str:
    """Truncate text to specified length.

    Args:
        text: Text to truncate
        max_length: Maximum length of resulting text (including suffix)
        suffix: String to append to truncated text

    Returns:
        Truncated text with suffix if needed
    """
    if len(text) <= max_length:
        return text
    return text[: max_length - len(suffix)] + suffix

normalize_whitespace

normalize_whitespace(text: str) -> str

Normalize whitespace in text.

Replaces multiple spaces, tabs, and newlines with single spaces and strips leading/trailing whitespace.

Parameters:

Name Type Description Default
text str

Text to normalize

required

Returns:

Type Description
str

Text with normalized whitespace

Source code in lex_helper/formatters/text.py
def normalize_whitespace(text: str) -> str:
    """Normalize whitespace in text.

    Replaces multiple spaces, tabs, and newlines with single spaces
    and strips leading/trailing whitespace.

    Args:
        text: Text to normalize

    Returns:
        Text with normalized whitespace
    """
    return " ".join(text.split())

split_into_sentences

split_into_sentences(text: str) -> list[str]

Split text into sentences.

Parameters:

Name Type Description Default
text str

Text to split

required

Returns:

Type Description
list[str]

List of sentences

Source code in lex_helper/formatters/text.py
def split_into_sentences(text: str) -> list[str]:
    """Split text into sentences.

    Args:
        text: Text to split

    Returns:
        List of sentences
    """
    # Basic sentence splitting - could be enhanced for edge cases
    sentences = re.split(r"(?<=[.!?])\s+", text.strip())
    return [s for s in sentences if s]  # Remove empty strings

Button Formatting

Create interactive buttons and quick replies for supported channels.

Single Button

Multiple Buttons

Button formatting utilities.

Classes

Button dataclass

Button(text: str, value: str)

Button configuration for response cards.

Functions

to_dict
to_dict() -> dict[str, str]

Convert button to dictionary format.

Returns:

Type Description
dict[str, str]

Dictionary representation of the button

Source code in lex_helper/formatters/buttons.py
def to_dict(self) -> dict[str, str]:
    """Convert button to dictionary format.

    Returns:
        Dictionary representation of the button
    """
    return {"text": self.text, "value": self.value}

Functions

create_button

create_button(text: str, value: str | None = None) -> Button

Create a button with text and optional value.

Parameters:

Name Type Description Default
text str

The button text to display

required
value str | None

The button value (defaults to text if not provided)

None

Returns:

Type Description
Button

A Button instance

Source code in lex_helper/formatters/buttons.py
def create_button(text: str, value: str | None = None) -> Button:
    """Create a button with text and optional value.

    Args:
        text: The button text to display
        value: The button value (defaults to text if not provided)

    Returns:
        A Button instance
    """
    return Button(text=text, value=value or text)

create_buttons

create_buttons(texts: list[str], values: list[str] | None = None) -> list[Button]

Create multiple buttons from lists of texts and optional values.

Parameters:

Name Type Description Default
texts list[str]

List of button texts

required
values list[str] | None

Optional list of button values (must match length of texts if provided)

None

Returns:

Type Description
list[Button]

List of Button instances

Raises:

Type Description
ValueError

If values list is provided but length doesn't match texts

Source code in lex_helper/formatters/buttons.py
def create_buttons(texts: list[str], values: list[str] | None = None) -> list[Button]:
    """Create multiple buttons from lists of texts and optional values.

    Args:
        texts: List of button texts
        values: Optional list of button values (must match length of texts if provided)

    Returns:
        List of Button instances

    Raises:
        ValueError: If values list is provided but length doesn't match texts
    """
    if values and len(values) != len(texts):
        raise ValueError("Values list must match length of texts list")

    if not values:
        return [create_button(text) for text in texts]

    return [create_button(text, value) for text, value in zip(texts, values)]

format_buttons_for_display

format_buttons_for_display(buttons: list[Button], style: str = 'default') -> str

Format buttons for display in a consistent way.

Parameters:

Name Type Description Default
buttons list[Button]

List of buttons to format

required
style str

Display style ("default", "compact", or "verbose")

'default'

Returns:

Type Description
str

Formatted string representation of buttons

Source code in lex_helper/formatters/buttons.py
def format_buttons_for_display(buttons: list[Button], style: str = "default") -> str:
    """Format buttons for display in a consistent way.

    Args:
        buttons: List of buttons to format
        style: Display style ("default", "compact", or "verbose")

    Returns:
        Formatted string representation of buttons
    """
    if not buttons:
        return ""

    if style == "compact":
        return ", ".join(button.text for button in buttons)

    if style == "verbose":
        return "\n".join(f"[{button.text}] -> {button.value}" for button in buttons)

    # Default style
    return " | ".join(f"[{button.text}]" for button in buttons)

buttons_to_dicts

buttons_to_dicts(buttons: list[Button]) -> list[dict[str, str]]

Convert a list of buttons to list of dictionaries.

Parameters:

Name Type Description Default
buttons list[Button]

List of Button instances

required

Returns:

Type Description
list[dict[str, str]]

List of button dictionaries

Source code in lex_helper/formatters/buttons.py
def buttons_to_dicts(buttons: list[Button]) -> list[dict[str, str]]:
    """Convert a list of buttons to list of dictionaries.

    Args:
        buttons: List of Button instances

    Returns:
        List of button dictionaries
    """
    return [button.to_dict() for button in buttons]

Button Formatting Utilities

Classes

Functions

format_buttons

format_buttons(buttons: list[Button]) -> list[Button]

This function formats Button objects.

Parameters: buttons (List[Button]): A list of Button objects to be formatted.

Returns: List[Button]: A list of formatted Button objects.

Source code in lex_helper/formatters/format_buttons.py
def format_buttons(buttons: list[Button]) -> list[Button]:
    """
    This function formats Button objects.

    Parameters:
    buttons (List[Button]): A list of Button objects to be formatted.

    Returns:
    List[Button]: A list of formatted Button objects.
    """
    return [Button(text=button.text, value=button.value or button.text) for button in buttons]

URL Handling

Utilities for processing and formatting URLs.

URL Formatting

URL formatting utilities.

Functions

is_valid_url

is_valid_url(url: str) -> bool

Check if a URL is valid.

Parameters:

Name Type Description Default
url str

URL to validate

required

Returns:

Type Description
bool

True if URL is valid, False otherwise

Source code in lex_helper/formatters/url.py
def is_valid_url(url: str) -> bool:
    """Check if a URL is valid.

    Args:
        url: URL to validate

    Returns:
        True if URL is valid, False otherwise
    """
    try:
        result = urlparse(url)
        return all([result.scheme, result.netloc])
    except:
        return False

normalize_url

normalize_url(url: str, default_scheme: str = 'https') -> str

Normalize a URL by adding scheme if missing.

Parameters:

Name Type Description Default
url str

URL to normalize

required
default_scheme str

Scheme to add if missing (default: "https")

'https'

Returns:

Type Description
str

Normalized URL

Source code in lex_helper/formatters/url.py
def normalize_url(url: str, default_scheme: str = "https") -> str:
    """Normalize a URL by adding scheme if missing.

    Args:
        url: URL to normalize
        default_scheme: Scheme to add if missing (default: "https")

    Returns:
        Normalized URL
    """
    if not url:
        return url

    try:
        result = urlparse(url)
        if not result.scheme:
            # Add scheme if missing
            url = f"{default_scheme}://{url}"
            result = urlparse(url)
        return urlunparse(result)
    except:
        return url

extract_domain

extract_domain(url: str) -> str | None

Extract domain from URL.

Parameters:

Name Type Description Default
url str

URL to extract domain from

required

Returns:

Type Description
str | None

Domain name or None if URL is invalid

Source code in lex_helper/formatters/url.py
def extract_domain(url: str) -> str | None:
    """Extract domain from URL.

    Args:
        url: URL to extract domain from

    Returns:
        Domain name or None if URL is invalid
    """
    try:
        result = urlparse(url)
        return result.netloc or None
    except:
        return None

build_url

build_url(scheme: str, netloc: str, path: str = '', params: str = '', query: str = '', fragment: str = '') -> str

Build a URL from components.

Parameters:

Name Type Description Default
scheme str

URL scheme (e.g., "https")

required
netloc str

Network location/hostname

required
path str

URL path

''
params str

URL parameters

''
query str

Query string

''
fragment str

Fragment identifier

''

Returns:

Type Description
str

Complete URL

Source code in lex_helper/formatters/url.py
def build_url(
    scheme: str,
    netloc: str,
    path: str = "",
    params: str = "",
    query: str = "",
    fragment: str = "",
) -> str:
    """Build a URL from components.

    Args:
        scheme: URL scheme (e.g., "https")
        netloc: Network location/hostname
        path: URL path
        params: URL parameters
        query: Query string
        fragment: Fragment identifier

    Returns:
        Complete URL
    """
    components = ParseResult(
        scheme=scheme,
        netloc=netloc,
        path=path,
        params=params,
        query=query,
        fragment=fragment,
    )
    return urlunparse(components)

clean_url

clean_url(url: str) -> str

Clean a URL by removing unnecessary components.

Removes fragments, normalizes scheme, ensures single slashes.

Parameters:

Name Type Description Default
url str

URL to clean

required

Returns:

Type Description
str

Cleaned URL

Source code in lex_helper/formatters/url.py
def clean_url(url: str) -> str:
    """Clean a URL by removing unnecessary components.

    Removes fragments, normalizes scheme, ensures single slashes.

    Args:
        url: URL to clean

    Returns:
        Cleaned URL
    """
    try:
        result = urlparse(url)
        cleaned = ParseResult(
            scheme=result.scheme or "https",
            netloc=result.netloc,
            path=result.path.replace("//", "/"),
            params=result.params,
            query=result.query,
            fragment="",  # Remove fragment
        )
        return urlunparse(cleaned)
    except:
        return url

URL Validation

URL Conversion

Text Processing Utilities

Additional text processing and cleaning utilities.

HTML Tag Removal

Functions

remove_html_tags

remove_html_tags(text: str) -> str
This function removes <p></p> HTML tags from the text and trims

from the end.

Parameters:
text (str): The text from which <p></p> HTML tags should be removed.

Returns:
str: The text without the <p></p> HTML tags and trailing

.

Source code in lex_helper/formatters/remove_html_tags.py
def remove_html_tags(text: str) -> str:
    """
    This function removes <p></p> HTML tags from the text and trims \r\n from the end.

    Parameters:
    text (str): The text from which <p></p> HTML tags should be removed.

    Returns:
    str: The text without the <p></p> HTML tags and trailing \r\n.
    """

    # Remove HTML tags
    text = re.sub(r"<p>(.*?)</p>", r"\1", text, flags=re.DOTALL)

    # Trim \r\n from the end of the text
    text = text.rstrip("\r\n")

    return text

Special Character Handling

Functions

replace_special_characters

replace_special_characters(text: str) -> str

This function replaces &amp," from the text.

Parameters: text (str): The text from which special characters should be removed.

Returns: str: The text without the special characters.

Source code in lex_helper/formatters/replace_special_characters.py
def replace_special_characters(text: str) -> str:
    """
    This function replaces &amp,&quot; from the text.

    Parameters:
    text (str): The text from which special characters should be removed.

    Returns:
    str: The text without the special characters.
    """

    # Replace special characters
    text = (
        text.replace("&amp;", "&")
        .replace("&quot;", '"')
        .replace("\u00a0", " ")
        .strip()
        .replace("&nbsp;", "")
        .replace("<br/>", "")
        .replace("<br />", "")
    )

    return text

Template Substitution

Usage Examples

Text Formatting

from lex_helper.formatters.text import remove_html_tags, substitute_keys_in_text

# Clean HTML from text
clean_text = remove_html_tags("<p>Hello <b>world</b>!</p>")
# Result: "Hello world!"

# Substitute variables in text
template = "Hello {name}, your order #{order_id} is ready!"
substitutions = {"name": "Alice", "order_id": "12345"}
message = substitute_keys_in_text(template, substitutions)
# Result: "Hello Alice, your order #12345 is ready!"

Button Creation

from lex_helper.formatters.buttons import create_buttons
from lex_helper.formatters.button import create_button

# Create a single button
button = create_button("Click me", "button_value")

# Create multiple buttons
buttons = create_buttons([
    ("Option 1", "value1"),
    ("Option 2", "value2"),
    ("Option 3", "value3")
])

URL Processing

from lex_helper.formatters.url import format_url
from lex_helper.formatters.is_valid_url import is_valid_url

# Validate URL
if is_valid_url("https://example.com"):
    formatted = format_url("https://example.com", "Visit Example")

Channel Compatibility

Different formatters work with different channels:

  • Text formatters: Work with all channels
  • Button formatters: Work with Lex and web channels, fallback to text for SMS
  • URL formatters: Automatically adapt based on channel capabilities

Next: Explore the Exceptions API for error handling utilities.