Python 用字符串数组替换字符串
假设我有一个字符串sPython 用字符串数组替换字符串,python,string,list,replace,Python,String,List,Replace,假设我有一个字符串s s = "?, ?, ?, test4, test5" 我知道有三个问号,我想用下面的数组相应地替换每个问号 replace_array = ['test1', 'test2', 'test3'] 取得 output = "test1, test2, test3, test4, test5" Python中是否有类似于s.magic\u replace\u func(*replace\u array)的函数可以达到预期的目标 谢谢 使用str.replace并将'?'
s = "?, ?, ?, test4, test5"
我知道有三个问号,我想用下面的数组相应地替换每个问号
replace_array = ['test1', 'test2', 'test3']
取得
output = "test1, test2, test3, test4, test5"
Python中是否有类似于s.magic\u replace\u func(*replace\u array)
的函数可以达到预期的目标
谢谢 使用
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'
使用str.replace()
进行限制,并循环:
for word in replace_array:
s = s.replace('?', word, 1)
演示:
如果输入字符串不包含任何大括号,也可以用{}
占位符替换卷曲问号,并使用str.format()
:
演示:
如果实际输入文本已包含{
和}
字符,则需要先转义这些字符:
s = s.replace('{', '{{').replace('}', '}}').replace('?', '{}').format(*replace_array)
演示:
使用函数方法的正则表达式只扫描字符串一次,在调整替换模式方面更灵活,不可能与现有的格式化操作冲突,如果没有足够的替换可用,可以更改为提供默认值…:
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
试试这个:
s.replace('?', '{}').format(*replace_array)
=> 'test1, test2, test3, test4, test5'
更好的是,如果用占位符替换
?
符号,则可以直接调用format()
,而无需先调用replace()
。在那之后,format()
会处理一切。这就是我的想法,尽管我不喜欢正则表达式,所以我选择了来替换iter(替换数组)
和'.join([c if c!='?'else下一步(替换)来替换s中的c])
。我不得不承认,使用正则表达式更适合被替换的模式。
s = s.replace('{', '{{').replace('}', '}}').replace('?', '{}').format(*replace_array)
>>> s = "{?, ?, ?, test4, test5}"
>>> s.replace('{', '{{').replace('}', '}}').replace('?', '{}').format(*replace_array)
'{test1, test2, test3, test4, test5}'
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
s.replace('?', '{}').format(*replace_array)
=> 'test1, test2, test3, test4, test5'