哪一种是替换通过复制转义的字符的最有吸引力的方法?

2024-06-06 01:13:11 发布

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

我正在寻找一个pythonic和有效的替代品,用于以下自我解释的代码:

term = "< << >" # turn this into "( < )"
term.replace("<<", "#~").replace(">>", "~#").replace(">", ")").replace("<", "(").replace("#~", "<").replace("~#", ">")

有什么想法吗?你知道吗


Tags: 代码替代品thispythonicreplaceturnterminto
3条回答

我会把所有的替换项放在一个列表中,然后迭代并替换:

CHARS = [
  ('<<', '#~'),
  ('>>', '~#'),
  ...
]

for replace in CHARS:
   term = term.replace(*replace)

不确定它是不是最像Python,但似乎很清楚。您甚至可以考虑接收字符列表的forloop。你知道吗

这里有一个比我第一个答案简短的方法。它将折叠字符序列上的输入拆分以删除它们,然后用替换的单个字符重新连接这些段。和以前一样,它使用字典来指定应该进行的替换。你知道吗

def convert(s, replacements):
    for before, after in replacements.items():
        s = before.join([segment.replace(before, after) for segment in s.split(before + before)])
    return s

>>> convert('< << >', {'<': '(', '>': ')'})
'( < )'

使用正则表达式:

import re
d = {'<': '(', '>': ')'}
replaceFunc = lambda m: m.group('a') or d[m.group('b')]
pattern = r"((?P<a><|>)(?P=a)|(?P<b><|>))"
term = "< << >"

replaced = re.sub(pattern, replaceFunc, term) #returns "( < )"

根据Niklas B.的建议编辑

上述正则表达式等价于匹配:

("<<" OR ">>") OR ("<" OR ">")

(?P<a><|>) #tells the re to match either "<" or ">", place the result in group 'a'
(?P=a) #tells the re to match one more of whatever was matched in the group 'a'
(?P<b><|>) #tells the re to match a sing "<" or ">" and place it in group 'b'

实际上,lambda函数replaceFunc只是重复这个匹配序列,但返回相关的替换字符。你知道吗

这个re匹配“最大组优先”,因此"<<< >"将转换为"<( )"。你知道吗

相关问题 更多 >