代替迭代在Python

问题描述 投票:0回答:6

我想替换字符串值不同(从字典)的出现。

string = 'asfd @@@ fdsfd @@@ ffds @@@ asdf'
kv = {1: 'hi', 2: 'there', 3: 'bla'}

预期:

string = 'asfd hi fdsfd there ffds bla asdf'

我试过几个解决方案,特别是与.replace或应用re.sub但仍然没有找到一个很好的一个。

python regex
6个回答
7
投票

一个单行溶液:

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是一个坏主意)和代码只有一行。此外这也工作时'@@@'的数目是较少**或大于**,指定在kvcount参数当在str.replace值的数量。


这导致我的解决方案的最终和99%的故障安全的变体,使用dict作为len count参数的replace

string.replace('@@@', '{}', len(kv)).format(*kv.values())

3
投票

这是使用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)

MoreInfo


2
投票

您可以使用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

0
投票
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

0
投票
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'

-1
投票
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
© www.soinside.com 2019 - 2024. All rights reserved.