def format_quantity(q, fmt="{:g}", ufmt="{:s}", u=None, basefmt="{value:s} {unit:s}"):
    """Use format strings to format a quantity.
    
    :param astropy.units.Quantity q: The quantity object to format.
    :param str fmt: The value format string.
    :param str ufmt: The unit format string.
    :param u: The unit to convert to. If ``None``, no conversion will occur.
    """
    
    if u is not None:
        q = q.to(u)
    
    try:
        string = basefmt.format(
            value = fmt.format(q.value),
            unit = ufmt.format(q.unit)
        )
    except ValueError:
        string = basefmt.format(
            value = repr(q.value),
            unit = ufmt.format(q.unit)
        )
    return string