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.
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)
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.
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)