I've written my custom implementation of an f""
/ .format(...)
. I started the project thinking it was going to be longer than three lines.
from typing import List, Union, AnyStr
def format_string(string: str, variables: List[Union[str, int, float, bool, complex]]) -> str:
"""
Formats the passed string with the passed list of variables
>>> format_string("Hello, [*]", ["Ben"])
Hello, Ben
:param string -> str: String to be formatted
:param variables -> List[Union[str, int, float, bool, complex]]: List of variables to format into string
:return str: Formatted string
"""
for index, value in enumerate(variables):
string = string.replace("[*]", str(value), 1)
return string
My main question is if it's possible to make this a one-liner. It absolutely infuriates me that I have to use three. I spent a long time trying a mixture of *
and ''.join
to no avail. The code works, I would just like to shorten it up to one line. Of course, any and all feedback is appreciated and considered.
A secondary question is the method header. To represent variables
, I have a List
that can contain any types of variables. How would I go about representing this instead of having to list each type separately?