繁体   English   中英

Python - 只替换字符串中的字母一次

[英]Python - replace letters in a string only once

我需要弄清楚如何在 python 中只替换一次字母。

例子:

s = "a b c d b"

# change letter 'a' to "bye" and letter 'b' to "hay"
# .replace function is problematic because:

s = s.replace('a', "bye")
print(s)

# will print to "bye b c d b" now if I try to replace letter b 
# it will replace the first b of "bye" aswell thats not what I want
# output I want: "bye hay c d hay"

任何帮助表示赞赏

您可以使用re.sub ,如下所示:

import re

s = "a b c d b"


def repl(e, lookup={"a": "bye", "b": "hay"}):
    return lookup.get(e.group(), e.group)


result = re.sub("[ab]", repl, s)
print(result)

输出

bye hay c d hay

引用sub的文档:

返回通过替换 repl 替换 string 中最左边的不重叠模式出现的字符串。 如果未找到模式,则返回字符串不变。 repl 可以是字符串或函数

如果您知道原始字符串中不存在的字符,最简单的方法(不需要额外的包)是将所有字符替换为那些“临时”字符,然后替换这些临时字符。 例如:

s = 'a b c d b'

s = s.replace('a', '\0').replace('b', '\1') # Put temporary characters
s = s.replace('\0', 'bye').replace('\1', 'hay') # Replace temporary characters

我喜欢 Dani Mesejo 的使用re.sub的建议,但我发现包装在一个方便的函数中时更容易使用,如下所示:

import re

def multi_replace(text, changes):
    return re.sub(
        '|'.join(changes),
        lambda match: changes[match.group()],
        text
    )
    
text = 'a b c d b'
changes = {'a': 'bye', 'b': 'hay'}

text = multi_replace(text, changes)
print(text)

输出:

bye hay c d hay

您可以简单地使用任何文本和更改字典作为输入调用multi_replace() ,即使是动态生成的,它也会很高兴地返回更新的文本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM