用字符串数组替换字符串

3

假设我有一个字符串 s

s = "?, ?, ?, test4, test5"

我知道有三个问号,我想将每个问号替换为以下数组中的相应元素

replace_array = ['test1', 'test2', 'test3']

获取
output = "test1, test2, test3, test4, test5"

有没有Python中的函数,类似 s.magic_replace_func(*replace_array) 这样,可以实现所需的目标?
谢谢!
4个回答

5

使用str.replace方法,将'?'替换成'{}',然后你就可以简单地使用str.format方法:

>>> s = "?, ?, ?, test4, test5"
>>> replace_array = ['test1', 'test2', 'test3']
>>> s.replace('?', '{}', len(replace_array)).format(*replace_array)
'test1, test2, test3, test4, test5'

4

使用str.replace()并带有限制的循环:

for word in replace_array:
    s = s.replace('?', word, 1)

示例:

>>> s = "?, ?, ?, test4, test5"
>>> replace_array = ['test1', 'test2', 'test3']
>>> for word in replace_array:
...     s = s.replace('?', word, 1)
... 
>>> s
'test1, test2, test3, test4, test5'

如果你的输入字符串没有大括号,还可以将大括号替换为 {} 占位符,并使用 str.format()

s = s.replace('?', '{}').format(*replace_array)

演示:

>>> s = "?, ?, ?, test4, test5"
>>> s.replace('?', '{}').format(*replace_array)
'test1, test2, test3, test4, test5'

如果您的实际输入文本已经包含 {} 字符,则需要先对其进行转义:
s = s.replace('{', '{{').replace('}', '}}').replace('?', '{}').format(*replace_array)

示例:

>>> s = "{?, ?, ?, test4, test5}"
>>> s.replace('{', '{{').replace('}', '}}').replace('?', '{}').format(*replace_array)
'{test1, test2, test3, test4, test5}'

2

使用带有函数方法的正则表达式——只扫描一次字符串,更加灵活地适应替换模式,不会与现有格式操作产生冲突,并且可以根据需要更改以提供默认值,如果没有足够的替换可用...:

import re

s = "?, ?, ?, test4, test5"
replace_array = ['test1', 'test2', 'test3']
res = re.sub('\?', lambda m, rep=iter(replace_array): next(rep), s)
#test1, test2, test3, test4, test5

1
这是我当时的想法,尽管我不喜欢正则表达式,但我使用了 to_replace = iter(replace_array)''.join([c if c != '?' else next(to_replace) for c in s])。使用正则表达式更适用于被替换的模式,我必须承认。 - DSM

2

试试这个:

s.replace('?', '{}').format(*replace_array)
=> 'test1, test2, test3, test4, test5'

更好的是,如果你用 {} 占位符替换掉 ? 标志,你可以直接调用 format(),无需先调用 replace()。之后,format() 会处理一切事情。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接