Python function call inside string formatting throws an error

a = ";"
b = ["foo","bar"]
c = f"{a.join(b)}" #works properly "foo;bar"

d = {"a":a, "b":b}
c = "{a.join(b)}".format(**d) #CRASH

Error: AttributeError: ‘str’ object has no attribute ‘join(b)’

Is there any way to make the second version work? Call .format on a string and have .join work.

>Solution :

Unfortunately, the format function is not a full-blown python interpreter, it can only access the properties of the given objects, but not execute code. If you want to format your string with the format syntax, you can do it in the following way:

a = ";"
b = [ "foo", "bar" ]
c = "{}".format(a.join(b))

Leave a Reply