from typing import Any


def tag(name: str, *args: Any, cap: bool = True, esc: bool = True, **kwargs: dict) -> str:
    """Makes an HTML tag

    :param name: Tag name
    :param *args: The contents of the tag, must have __str__ method
    :param cap: Should the tag have an end?
    :param **kwargs: Tag attributes
    :returns: String of a formatted HTML tag
    """
    escchar = ("\n" if esc else "")
    attrs = "".join(
        f" {k.strip('_')}='{v}'"
        for k, v in kwargs.items()
    )
    start = f"<{name}{attrs}>"
    middle = "".join(map(str, args)).strip() + (escchar if args else "")
    end = (f"</{name}>{escchar}" if cap else "")
    return f"{start}{escchar}{middle}{end}"