Python中的迭代替换

2024-10-01 13:38:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

期望:

^{pr2}$

我试过几种解决方案,特别是用。替换或re.sub公司但还是没找到好的。在


Tags: 字符串restring字典公司解决方案hithere
3条回答

一线解决方案:

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

简短说明:

  • 将所有'@@@'字符串替换为python字符串格式标识符'{}'len(kv)将替换的数量减少到dict的长度,当dict的元素少于字符串中的'@@@'时,避免{}
  • 使用kv.values()提取字典值
  • *kv.values()解压字典值,并将其作为参数传递给string format方法。在

示例代码执行:
输入

^{pr2}$

和输出

string.replace('@@@', '{}', len(kv)).format(*kv.values())
#Out: 'asfd hi fdsfd there ffds bla asdf'

此解决方案的优点: 没有显式循环(显式循环在python中几乎总是一个坏主意),只有一行代码。此外,当'@@@'中的'@@@'的数目小于**或大于kv**中的值数目时,当str.replace中的count参数被指定时,也起作用。在


这导致了我的解决方案的最终和99%故障保护变体,使用dict的len作为^{中的count参数:

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)

MoreInfo

您可以使用re.sub完成任何排序

Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed.

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))

输出

^{pr2}$

相关问题 更多 >