Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python function call inside string formatting throws an error

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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))
print(c)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading