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 invalues
You can replace the ?
with {}
and call format
:
print(mystr.replace("?", "'{}'").format(*values))
#MY VALUES ARE: ('a', 'b', 'f', '12')
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] )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.