e.g. I have 2 py script, namely main.py
and stringhelper.py
.
Since print(f'{student_{i}_{j}}')
cannot be read in IDE if variable student_1_2
exist and if i=1
,j=2
,
I want to make a function that can print 'x{a{h}b{i}c{j}z}y'
by changing the string to
exec('''temp_s = 'a{}b{}c{}z'.format(h,i,j)''') # where I suppose e.g. h can refer to main.h but cannot
exec('''print('x{}y'.format(f'{temp_s}')'''
In
stringhelper.py
import re
def execprintf(s):
if s.find('{')<0:
print(s)
exec('''print(s)''')
else:
# use re to do sth to recongize {...{...{ case
if conditionA: # {...{...{ case
print('warning for input s')
elif conditionB: # ... {...{ case
# not finished
# not writing as I meet some problem for simple '{h}' case below
pass
else:
ss = re.split('{|}',s)
ss_even = ss[0::2]
ss_odd = ss[1::2]
s_wo_args = '{}'.join(ss_even)
s_args = ', '.join(ss_odd)
exec('''print(s_wo_args.format('''+s_args+'''))''')
In
main.py
from stringhelper.py import execprintf
h = 1
execprintf('{h}') # NameError: name 'h' is not defined
If I copy the execprintf
function into main.py
and does not import
from stringhelper.py
, it can read h and display 1.
Is it possible to read the h in stringhelper.py?
I need at least exceprintf('a{h}b{i}c{j}d')
can run correctly first.