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
-
1You're leaving yourself open to SQL injection. Don't do this.cs95– cs952019年06月05日 14:38:03 +00:00Commented Jun 5, 2019 at 14:38
2 Answers 2
You can replace the ? with {} and call format:
print(mystr.replace("?", "'{}'").format(*values))
#MY VALUES ARE: ('a', 'b', 'f', '12')
Comments
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
join is faster with list comprehensions than generators.