I am trying to replace variables in a query with their actual values but I need it to have the ability to replace a variable with AND without strings around it (since this query will be executed, the type should be correct). This is being done using Python 3.8.
An example of my code is as follows:
query = 'My first variable is ?ONE and has quotes around it. \nMy second variable is ?!TWO and has no quotes around it.'
print("ORIGINAL QUERY: ")
print(query + '\n')
params = { 'ONE' : '2020-01-01', 'TWO': '2020-06-01'}
print("PARAMS:")
print(str(params) + '\n')
print("Replacing variables...")
for key in params.keys():
new_execute = query.replace(('?!' + key), params[key]) # Replace this specific prefix so that we can place the non-string variables.
new_execute = query.replace(('?' + key), "\'" + params[key] + "\'")
query = new_execute
print("NEW QUERY")
print(query + '\n')
The final output should look like the following:
My first variable is '2020-01-01' and has quotes around it.
My second variable is 2020-06-01 and has no quotes around it.
Using this code however, results in the following output instead:
My first variable is '2020-01-01' and has quotes around it.
My second variable is ?!TWO and has no quotes around it.
Is there any way to fix this? I've tried altering how I make the prefix in the .replace() function but that had no effect.