我想替换字符串值不同(从字典)的出现。
string = 'asfd @@@ fdsfd @@@ ffds @@@ asdf'
kv = {1: 'hi', 2: 'there', 3: 'bla'}
预期:
string = 'asfd hi fdsfd there ffds bla asdf'
我试过几个解决方案,特别是与.replace或应用re.sub但仍然没有找到一个很好的一个。
一个单行溶液:
string.replace('@@@', '{}', len(kv)).format(*kv.values())
简短的说明:
'@@@'
所有'{}'
字符串。 len(kv)
降低内容替换到字典的长度的数目,避免IndexError
当字典具有比'@@@'
的字符串中的数字更少的元件kv.values()
字典中的值*kv.values()
并通过此作为参数传递给串format
方法。示例代码执行: 输入
string = 'asfd @@@ fdsfd @@@ ffds @@@ asdf'
kv = {'1': 'hi', '2': 'there', '3': 'bla'}
和输出
string.replace('@@@', '{}', len(kv)).format(*kv.values())
#Out: 'asfd hi fdsfd there ffds bla asdf'
该解决方案的优势:没有明确的循环(循环明确几乎总是在Python是一个坏主意)和代码只有一行。此外这也工作时'@@@'
的数目是较少**或大于**,指定在kv
的count
参数当在str.replace
值的数量。
这导致我的解决方案的最终和99%的故障安全的变体,使用dict作为len
count
参数的replace
:
string.replace('@@@', '{}', len(kv)).format(*kv.values())
这是使用str.replace
可选参数count
一种方法。
例如:
s = 'asfd @@@ fdsfd @@@ ffds @@@ asdf'
kv = {'1': 'hi', '2': 'there', '3': 'bla'}
for k, v in sorted(kv.items()):
s = s.replace("@@@", v, 1)
print(s)
您可以使用re.sub
得到与任何排序完成任务
返回由替换REPL替换字符串模式的最左边的非重叠出现所获得的字符串。如果未找到模式,串原封不动地返回。 REPL可以是一个字符串或一功能;如果它是一个字符串,任何反斜杠在它被处理。
import re
string = 'asfd @@@ fdsfd @@@ ffds @@@ asdf'
kv = {'1': 'hi', '2': 'there', '3': 'bla'}
class repl:
def __init__(self):
self.called=0
def __call__(self,match):
self.called+=1
return kv[str(self.called)]
print(re.sub('@@@',repl(),string))
OUTPUT
asfd hi fdsfd there ffds bla asdf
string = 'asfd @@@ fdsfd @@@ ffds @@@ asdf'
kv = {1: 'hi', 2: 'there', 3: 'bla'}
for k,v in kv.items():
string = string.replace('@@@', v, 1)
print(string)
OUTPUT:
asfd hi fdsfd there ffds bla asdf
kv = {'1': 'hi', '2': 'there', '3': 'bla'}
string = 'asfd @@@ fdsfd @@@ ffds @@@ asdf'
string_list=string.split('@@@')
string_list_out=[]
for i in range(len(string_list)):
if i==0:
string_list_out.append(string_list[0])
else:
string_list_out.append(kv[str(i)])
string_list_out.append(string_list[i])
string_list_out=''.join(string_list_out)
print(string_list_out)
'asfd hi fdsfd there ffds bla asdf'
import re
string = 'asfd @@@ fdsfd @@@ ffds @@@ asdf'
kv = {1: 'hi', 2: 'there', 3: 'bla'}
counter = 1
def data_():
global counter
str_replace = kv[counter]
counter += 1
return str_replace
print(re.sub(r'@@@', data_(), string))
>>> asfd hi fdsfd there ffds bla asdf