1

I tried using the code below, but i still have the ' ' around each element in the string.

l = ['a','b','c']
query = "SELECT " + str(l).strip('[,]') + " FROM table"

returns

"SELECT 'a', 'b', 'c' FROM table"

How can I fix this?

4
  • 1
    How would you make a comma-separated string from a list of strings? (Not hammering as dupe because this is SQL and building SQL commands from variables is probably bad) Commented Jun 15, 2018 at 20:30
  • I have txt file with a list of variables. What would the preferred way to build the query? @Aran-Fey Commented Jun 15, 2018 at 20:34
  • 1
    use a library like pypika Commented Jun 15, 2018 at 20:37
  • Did you check what does strip() do first? Commented Jun 15, 2018 at 20:42

2 Answers 2

2

Using str.join:

query = "SELECT " + ", ".join(l) + " FROM table"

print(query)

"SELECT a, b, c FROM table"

As pointed out, forming SQL queries from strings should be a last resort.

Sign up to request clarification or add additional context in comments.

2 Comments

This is only safe if you are positive that l actually contains only valid columns names. (Also, it returns the same string the OP already has.)
@chepner, Yep. We're making several assumptions, e.g. table exists, the column list reflects valid table fields.
0

you can use join :-

l = ['a','b','c']
query = "SELECT '" + l.join('') + "' FROM table"

print(query)

"SELECT 'abc' FROM table"

if you want them to join you can use the above code.

Comments

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.