How does Python support randomly chosen variable names?

Issue

In Flask there is the following code:

{% extends "base.html" %}

{% block content %}
<h1 class="title">
  Welcome,{{ anyweirdname }}!
</h1>
{% endblock %}

You can render this HTML file using:

render_template('text.html', anyweirdname = "foo")

How can such syntatic sugar be implemented using Python? In other words, how can the computer know, that at {{ anyweirdname }} has to be replaced using anyweirdname = "foo"

Obviously this is not possible in languages like C, because C does not change its compilation by using another variable name. One would presume that the code used with other variable names – basically an isomorphism – would be indifferent, but it is obviously not.

Solution

If I understand you correctly, you are looking for a string where you can you can substitute variable names directly.

This can be done in Python 3.0+ using f-strings:

anyweirdname = 'foo'
print(f"Hello, {anyweirdname}")

Basically, you write f in front of the string where you want a variable substituted.
If this indeed is what you asked, you can find more information in this article.

Answered By – data.dude

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published