-1

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.

Matthew G
  • 3
  • 2
  • Strings are immutable. The first `query.replace` doesn't change `query`, it puts the result in `new_execute`. _That's_ what you need to run your next replace on. [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – Pranav Hosangadi Sep 28 '20 at 20:33
  • That fixed it! Thank you so much! Silly little bug on my part. – Matthew G Sep 28 '20 at 20:34
  • Duplicate of [Why doesn't calling a Python string method do anything unless you assign its output?](https://stackoverflow.com/questions/9189172/why-doesnt-calling-a-python-string-method-do-anything-unless-you-assign-its-out)? – Pranav Hosangadi Sep 28 '20 at 20:36
  • Does this answer your question? [Why doesn't calling a Python string method do anything unless you assign its output?](https://stackoverflow.com/questions/9189172/why-doesnt-calling-a-python-string-method-do-anything-unless-you-assign-its-out) – AMC Sep 28 '20 at 22:29

1 Answers1

2

Both your replace() calls are operating on query. So the second replacement doesn't incorporate the changes made from the first replacement.

There's no need for the new_execute variable, just store the result of the replacements back in query.

for key in params.keys():
    query = query.replace(('?!' + key), params[key])               # Replace this specific prefix so that we can place the non-string variables.
    query = query.replace(('?' + key), "\'" + params[key] + "\'")
Barmar
  • 741,623
  • 53
  • 500
  • 612