3

I'm new to Python and I would like to create a string like this :

print("{} INNER JOIN {}".format(table1, table2))

The problem is that table1 and table2 are stored in a list tables_list = ['table1','table2'] and I don't know how many values there are in that list, so if I only have one item in that list, the result of the print would be :

table1

without the join.

I guess I should be looping on tables_list but I can't seem to figure out how to use format in that case. Any help would be appreciated.

3 Answers 3

2

You can use join combined with slicing.

" INNER JOIN ".join(tables_list[:2])

Though it looks like you are trying to build an SQL query, so I'd warn you you should be wary of rolling your own query builder. Look in to the docs for whichever DB library you are using to make sure you aren't rewriting things they can already do for you.

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

Comments

1

You can do it like this:

>>> tables_list = ['table1','table2']
>>> print("{} INNER JOIN {}".format(*tables_list))
table1 INNER JOIN table2

Comments

1

It looks like you are writing SQL. To help mitigate the risk of getting SQL injected most Python database libraries offer their own form of string formatting, (a.k.a bind variables). Utilizing bind variables in Python usually looks like this.

query_results = cursor.execute("?INNER JOIN ?", ("table1", "table2"))

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.