hory
hory

Reputation: 305

Inserting elements from array to the string

I have two variables:

query = "String: {} Number: {}"
param = ['text', 1]

I need to merge these two variables and keep the quote marks in case of string and numbers without quote marks.

result= "String: 'text' Number: 1"

I tried to use query.format(param), but it removes the quote marks around the 'text'. How can I solve that?

Upvotes: 2

Views: 99

Answers (1)

Cory Kramer
Cory Kramer

Reputation: 117946

You can use repr on each item in param within a generator expression, then use format to add them to your string.

>>> query = "String: {} Number: {}"
>>> param = ['text', 1]
>>> query.format(*(repr(i) for i in param))
"String: 'text' Number: 1"

Upvotes: 7

Related Questions