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

Denis
  • 11,796
  • 16
  • 88
  • 150

2 Answers2

4

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

print(mystr.replace("?", "'{}'").format(*values))
#MY VALUES ARE: ('a', 'b', 'f', '12')
pault
  • 41,343
  • 15
  • 107
  • 149
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] )
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    the list comprehension version of the second snippet would not be as big. – Ma0 Jun 05 '19 at 14:48
  • 2
    Sorry for being pedantic but [we have it on good authority](https://stackoverflow.com/a/34822788/6162307) that `join` is faster with list comprehensions than generators. – Ma0 Jun 05 '19 at 14:52
  • I reacted the same way when I found out :)) – Ma0 Jun 05 '19 at 14:56