简体   繁体   English

使用列表中的索引替换字符串中的每个字符

[英]Replacing each character in a string using an index into a list

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 . 在列表中该索引处具有相应的值: values So first ? 那么首先? would be replaced with values[0] , second ? 将被替换为values[0] ,第二? would be replaced with values[1] 将被替换为values[1]

So my final str would look like: 所以我的最后一个str看起来像:

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

NOTE: The number of ? 注意:多少? will vary but it will always equal the number of values in values 会有所不同,但始终等于值中的values

You can replace the ? 您可以更换? with {} and call format : {}和呼叫format

print(mystr.replace("?", "'{}'").format(*values))
#MY VALUES ARE: ('a', 'b', 'f', '12')

This isn't sql, this just looks like it. 这不是sql,看起来像它。 Don't worry about SQL injection, it's not a concern here. 不必担心SQL注入,这里不必担心。

See https://bobby-tables.com/python for parametrized queries - for simply replacement use str.replace(old, new, count=1) 请参阅https://bobby-tables.com/python以进行参数化查询-只需替换即可使用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') 我的值是('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. 作为列表理解( 列表上的连接要快于生成器组件上的连接 )thx @Ev。 Kuonis : 库奥尼斯

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM