Python function call inside string formatting throws an error

Question:

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

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

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.

Asked By: xyz3lt

||

Answers:

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))
print(c)
Answered By: TopchetoEU
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.