2

Suppose I have the following string:

query = '''UPDATE table1 SET 'variable1' = 'value1', 'something' = "['bla', 'yada']", location = 'chicago' WHERE id = 9'''

This is a string that I will be using as an argument to a custom library to update a SQLite table. What I need to do is remove the single quotes around the word before each equal sign (if the word does have single quotes).

Desired output is as follows:

query = '''UPDATE table1 SET variable1 = 'value1', something = "['bla', 'yada']", location = 'chicago' WHERE id = 9'''

Notice the single quotes around words 'variable1' and 'something' have been removed. How can I do this for all queries in this form?

2
  • What do you mean by "all queries in this form?"? Which all queries are you talking about here? Commented May 10, 2021 at 22:36
  • 1
    Sorry, meant all queries that follow a similar structure to the example provided. Commented May 10, 2021 at 22:41

3 Answers 3

4

You could use a regex to replace those. The regex captures the values inside the single quotes if they are followed by a space and equals sign, then replaces the quote and value with just the value.

import re
query = '''UPDATE table1 SET 'variable1' = 'value1', 'something' = "['bla', 'yada']", location = 'chicago' WHERE id = 9'''

updated_query = re.sub(r"'([^']+)'(?=\s=)", r"\1", query)
print(query)
print(updated_query)

OUTPUT

UPDATE table1 SET 'variable1' = 'value1', 'something' = "['bla', 'yada']", location = 'chicago' WHERE id = 9
UPDATE table1 SET variable1 = 'value1', something = "['bla', 'yada']", location = 'chicago' WHERE id = 9
Sign up to request clarification or add additional context in comments.

Comments

1

How about splitting the query with commas. To get all different fields.

fields = query.split(", ")

then splitting each field by an = sign

fields = [i.split("=") for i in fields]

then removing the single quotes but only from the left hand side of the assignment operator

for f in fields:
    f[0] = f[0].replace("'", "")

then just going backwards and combining the strings

fields = ["=".join(f) for f in fields]
query = ", ".join(fields)

Comments

0

I would try the following:

words = query.split(" ")

new_query = ' '.join([words[i].replace("'", "") if words[i + 1] == '=' else words[i] for i in range(len(words) - 1)] + [words[len(words) - 1]])

1 Comment

This fails when there's a whitespace before the = sign.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.