Skip to content

is_slug()

slugany.is_slug

is_slug(s: str, separator: str = '-', *, allow_unicode: bool = False) -> bool

Check whether a string is a valid slug.

A valid slug contains only alphanumeric characters (ASCII or Unicode when allow_unicode is True) separated by the given separator, with no leading or trailing separators.

Parameters:

Name Type Description Default
s str

The string to validate.

required
separator str

The separator used in the slug. Defaults to "-". An empty separator disables separator handling.

'-'
allow_unicode bool

If True, allow Unicode word characters (\w) and emoji characters in addition to ASCII alphanumeric characters.

False

Returns:

Type Description
bool

True if the string is a valid slug, False otherwise.

Raises:

Type Description
TypeError

If s or separator is not a string.

ValueError

If separator contains alphanumeric or whitespace characters.

Examples:

>>> is_slug("hello-world")
True
>>> is_slug("hello world")
False
>>> is_slug("hello_world", separator="_")
True
Source code in slugany/_validator.py
def is_slug(s: str, separator: str = "-", *, allow_unicode: bool = False) -> bool:
    """Check whether a string is a valid slug.

    A valid slug contains only alphanumeric characters (ASCII or Unicode
    when ``allow_unicode`` is ``True``) separated by the given separator,
    with no leading or trailing separators.

    Args:
        s: The string to validate.
        separator: The separator used in the slug. Defaults to ``"-"``.
            An empty separator disables separator handling.
        allow_unicode: If ``True``, allow Unicode word characters (``\\w``)
            and emoji characters in addition to ASCII alphanumeric characters.

    Returns:
        ``True`` if the string is a valid slug, ``False`` otherwise.

    Raises:
        TypeError: If ``s`` or ``separator`` is not a string.
        ValueError: If ``separator`` contains alphanumeric or whitespace
            characters.

    Examples:
        >>> is_slug("hello-world")
        True
        >>> is_slug("hello world")
        False
        >>> is_slug("hello_world", separator="_")
        True
    """
    if not isinstance(s, str):
        msg = f"s must be a string, got {type(s).__name__}"
        raise TypeError(msg)
    if not isinstance(separator, str):
        msg = f"separator must be a string, got {type(separator).__name__}"
        raise TypeError(msg)
    if any(c.isalnum() for c in separator):
        msg = f"separator must not contain alphanumeric characters, got {separator!r}."
        raise ValueError(msg)
    if any(c.isspace() for c in separator):
        msg = "separator must not contain whitespace."
        raise ValueError(msg)
    if not s:
        return False
    return _slug_pattern(separator, allow_unicode).fullmatch(s) is not None