1

Suppose I have a string as follows:

mystr = "MY VALUES ARE: (?, ?, ?, ?)"
values = ['a', 'b', 'f', 12]

I would like replace each ? with the corresponding value at that index in the list: values. So first ? would be replaced with values[0], second ? would be replaced with values[1]

So my final str would look like:

MY VALUES ARE: ('a', 'b', 'f', '12')

NOTE: The number of ? will vary but it will always equal the number of values in values

1
  • 1
    You're leaving yourself open to SQL injection. Don't do this. Commented Jun 5, 2019 at 14:38

2 Answers 2

4

You can replace the ? with {} and call format:

print(mystr.replace("?", "'{}'").format(*values))
#MY VALUES ARE: ('a', 'b', 'f', '12')
Sign up to request clarification or add additional context in comments.

Comments

2

This isn't sql, this just looks like it. Don't worry about SQL injection, it's not a concern here.

See https://bobby-tables.com/python for parametrized queries - for simply replacement use str.replace(old, new, count=1)

sql = "My VALUES are (?, ?, ?, ?)"
values = ['a', 'b', 'f', 12]

for v in values:
    sql = sql.replace("?",f"'{v}'",1)  # inefficient - will create intermediate strings to
                                       # be replaced

print(sql)

Output:

My VALUES are ('a', 'b', 'f', '12')


Slightly more performant but more code as well:

sql = "My VALUES are (?, ?, ?, ?)"
values = ['a', 'b', 'f', 12]

k = iter(values)

# see list comp below for shorter approach
l = []  
for c in sql:
    if c != '?':
        l.append(c)
    else:
        l.append(f"'{next(k)}'")

sql = "".join(l)
print(sql)         # My VALUES are ('a', 'b', 'f', '12') as well

As list comprehension (join is faster on list then on generator comps) thx @Ev. Kuonis :

sql = "".join( [ c if c != '?' else f"'{next(k)}'" for c in sql] )

3 Comments

the list comprehension version of the second snippet would not be as big.
Sorry for being pedantic but we have it on good authority that join is faster with list comprehensions than generators.
I reacted the same way when I found out :))

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.