Python str formatting

Question:

I am using Python 3.8.10.

result = "<svg id='{id}' class='{class}' height='{height}{unit}' width='{width}{unit}'>".format(id=image_id, class=html_class, height=str(height), unit=unit_of_measure)

I get this error message:

 File "/home/michael/PycharmProjects/images_outer/images_project/images/templatetags/images.py", line 131
    result = "<svg id='{id}' class='{class}' height='{height}{unit}' width='{width}{unit}'>".format(id=image_id, class=html_class, height=str(height), unit=str(unit_of_measure))
                                                                                                                 ^
SyntaxError: invalid syntax
python-BaseException

Process finished with exit code 130 (interrupted by signal 2: SIGINT)

What can I try to resolve this?

Asked By: Trts

||

Answers:

if you are using python 3.x you can use f strings

result = f"<svg id='{id}' class='{class}' height='{height}{unit}' width='{width}{unit}'>"
Answered By: jackquin

class is a builtin keyword in python, so cannot be used in this context. Instead of str.format() use the alternative "f-string" syntax for formatting strings, e.g.:

result = f"<svg id='{image_id}' class='{html_class}' height='{height}{unit_of_measure}' width='{width}{unit_of_measure}'>"
Answered By: Bartosz Karwacki
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.