f"..." strings are great when interpolating expression results into a literal, but you don't have a literal, you have a template string in a separate variable.
You can use str.format() to apply values to that template:
name=["deep","mahesh","nirbhay"]
user_input = "certi_{element}" # this string i ask from user
for value in name:
print(user_input.format(element=value))
String formatting placeholders that use names (such as {element}) are not variables. You assign a value for each name in the keyword arguments of the str.format() call instead. In the above example, element=value passes in the value of the value variable to fill in the placeholder with the element.
Unlike f-strings, the {...} placeholders are not expressions and you can't use arbitrary Python expressions in the template. This is a good thing, you wouldn't want end-users to be able to execute arbitrary Python code in your program. See the Format String Syntax documenation for details.
You can pass in any number of names; the string template doesn't have to use any of them. If you combine str.format() with the **mapping call convention, you can use any dictionary as the source of values:
template_values = {
'name': 'Ford Prefect',
'number': 42,
'company': 'Sirius Cybernetics Corporation',
'element': 'Improbability Drive',
}
print(user_input.format(**template_values)
The above would let a user use any of the names in template_values in their template, any number of times they like.
While you can use locals() and globals() to produce dictionaries mapping variable names to values, I'd not recommend that approach. Use a dedicated namespace like the above to limit what names are available, and document those names for your end-users.
If you define:
def fstr(template):
return eval(f"f'{template}'")
Then you can do:
name=["deep","mahesh","nirbhay"]
user_input = r"certi_{element}" # this string i ask from user
for element in name:
print(fstr(user_input))
Which gives as output:
certi_deep
certi_mahesh
certi_nirbhay
But be aware that users can use expressions in the template, like e.g.:
import os # assume you have used os somewhere
user_input = r"certi_{os.environ}"
for element in name:
print(fstr(user_input))
You definitely don't want this!
Therefore, a much safer option is to define:
def fstr(template, **kwargs):
return eval(f"f'{template}'", kwargs)
Arbitrary code is no longer possible, but users can still use string expressions like:
user_input = r"certi_{element.upper()*2}"
for element in name:
print(fstr(user_input, element=element))
Gives as output:
certi_DEEPDEEP
certi_MAHESHMAHESH
certi_NIRBHAYNIRBHAY
Which may be desired in some cases.
Python 3.8 f-string = syntax
It has arrived!
#!/usr/bin/env python3
foo = 1
bar = 2
print(f"{foo=} {bar=}")
output:
foo=1 bar=2
You can also ask for spaces before/after the = sign on the output by simply adding spaces around = in {}thanks, e.g.
foo = 1
bar = 2
print(f"{foo = } {bar =}")
produces:
foo = 1 bar =2
This feature was added in commit https://github.com/python/cpython/commit/9a4135e939bc223f592045a38e0f927ba170da32 "Add f-string debugging using '='." which documents:
f-strings now support = for quick and easy debugging
-----------------------------------------------------
Add ``=`` specifier to f-strings. ``f'{expr=}'`` expands
to the text of the expression, an equal sign, then the repr of the
evaluated expression. So::
x = 3
print(f'{x*9 + 15=}')
Would print ``x*9 + 15=42``.
so it also works for arbitrary expressions. Nice!
Visual Studio Code snippet
I use a variant of this for every language/IDE I ever use to quickly add debug print statements, for Python VS Code it is:
"Print variable to console": {
"prefix": "pp",
"body": [
"print('${CLIPBOARD} = ' + str(${CLIPBOARD}))"
],
"description": "Log variable to console"
}
Then you can just select a variable name, Ctrl + C, put cursor somewhere, pp + Enter, and then you get:
print('variablename = ' + str(variablename))
For temporary debug statements, this or a variant of it is a huge time saver.
The dream: JavaScript-like dict keys from variable names
I find Python better than JavaScript in almost every sense, but I've grown to really like this JavaScript feature:
let abc = 1
let def = 2
console.log({abc, def})
works in JavaScript because {abc, def} expands to {abc: 1, def: 2}. This is just awesome, and gets used a lot in other places of the code besides logging.
Not possible nicely in Python currently except with locals: Python variables as keys to dict
You can just use eval:
def debug(variable):
print variable, '=', repr(eval(variable))
Or more generally (which actually works in the context of the calling function and doesn't break on debug('variable'), but only on CPython):
from __future__ import print_function
import sys
def debug(expression):
frame = sys._getframe(1)
print(expression, '=', repr(eval(expression, frame.f_globals, frame.f_locals)))
And you can do:
>>> x = 1
>>> debug('x + 1')
x + 1 = 2