Home > front end >  How to make string formatted afterwards
How to make string formatted afterwards

Time:03-25

I have a config.yaml which contains following:

SQL1: 'select * from {x1}'
SQL2: 'select * from {x2}'
SQL3: 'select * from {x3}'
SQL4: 'select * from {x2}'
SQL5: 'select * from {x1}'

Then I have my script (example):

x1 = 'test'
x2 = 'test2'
x3 = 'test3'

for sql in ['SQL1', 'SQL2', 'SQL3', 'SQL4', 'SQL5']:
    print(config[sql])

Desired output:

select * from test
select * from test2
select * from test3
select * from test2
select * from test

But this doesn't work. I need to tell Python somehow that the string which config['SQL1'] points to is a formatted string like f''

CodePudding user response:

KEY: 'Print my var: {x}'

You can do it easily if the brackets {} are empty, with the str method .format:

a = "Print my var: {}"
print(a.format(x))

You can achieve this using re (regex = REGular EXpression), and removing x from the string.


As I just read from documentation and from @jonrsharpe's comment, you can do it also passing x as a **kwarg of .format:

a = "Print my var: {x}"
print(a.format(x="Variable"))

If you don't know the name of the variable, you can estract it with regex as suggested above, remove it from the string leaving the {} empty, and then get its value this way:

print(a.format(globals()[variable_name_you_got_from_regex]))

CodePudding user response:

This might not scale, but based on your example and the current values this would work:

config = {
    "SQL1": "select * from {x1}",
    "SQL2": "select * from {x2}",
    "SQL3": "select * from {x3}",
    "SQL4": "select * from {x2}",
    "SQL5": "select * from {x1}",
}

x1 = "test"
x2 = "test2"
x3 = "test3"

for sql in ["SQL1", "SQL2", "SQL3", "SQL4", "SQL5"]:
    config_line = config[sql]
    config_line = config_line.replace('{x1}', x1)
    config_line = config_line.replace('{x2}', x2)
    config_line = config_line.replace('{x3}', x3)
    print(config_line)

The output is:

select * from test
select * from test2
select * from test3
select * from test2
select * from test

Another option is to use a template, modifying your input to match the template format.

from string import Template

config = {
    "SQL1": "select * from $x1",
    "SQL2": "select * from $x2",
    "SQL3": "select * from $x3",
    "SQL4": "select * from $x2",
    "SQL5": "select * from $x1",
}

replacement_mapping = {
    "x1": "test",
    "x2": "test2",
    "x3": "test3",
}
for sql in ["SQL1", "SQL2", "SQL3", "SQL4", "SQL5"]:
    config_line = config[sql]
    template = Template(config_line)
    print(template.substitute(**replacement_mapping))

Then you can pass a dictionary of the standin variables and their replacement values.

  • Related