python 与python中php的str_replace类似的功能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1391429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 22:07:21  来源:igfitidea点击:

similar function to php's str_replace in python?

python

提问by Mohamed

is there a similar function in python that takes search(array) and replace(array) as a parameter? Then takes a value from each array and uses them to do search and replace on subject(string).

python中是否有类似的函数将search(array)和replace(array)作为参数?然后从每个数组中获取一个值并使用它们对主题(字符串)进行搜索和替换。

I know I can achieve this using for loops, but just looking more elegant way.

我知道我可以使用 for 循环来实现这一点,但只是看起来更优雅。

回答by John Fouhy

I believe the answer is no.

我相信答案是否定的。

I would specify your search/replace strings in a list, and the iterate over it:

我会在列表中指定您的搜索/替换字符串,并对其进行迭代:

edits = [(search0, replace0), (search1, replace1), (search2, replace2)] # etc.
for search, replace in edits:
    s = s.replace(search, replace)

Even if python did have a str_replace-style function, I think I would still separate out my search/replace strings as a list, so really this is only taking one extra line of code.

即使 python 确实有一个str_replace-style 函数,我想我仍然会将我的搜索/替换字符串作为一个列表分开,所以这实际上只需要多一行代码。

Finally, this is a programming language after all. If it doesn't supply the function you want, you can always define it yourself.

最后,这毕竟是一种编程语言。如果它没有提供你想要的功能,你总是可以自己定义它。

回答by Anon

Heh - you could use the one-liner below whose elegance is second only to its convenience :-P

呵呵 - 你可以使用下面的单线,它的优雅仅次于它的方便:-P

(Acts like PHP when search is longer than replace, too, if I read that correctly in the PHP docs.):

(如果我在 PHP 文档中正确阅读了这一点,那么当搜索时间长于替换时,行为也像 PHP。):

**** Edit: This new version works for all sized substrings to replace. ****

**** 编辑:这个新版本适用于所有大小的子字符串来替换。****

>>> subject = "Coming up with these convoluted things can be very addictive."
>>> search = ['Coming', 'with', 'things', 'addictive.', ' up', ' these', 'convoluted ', ' very']
>>> replace = ['Making', 'Python', 'one-liners', 'fun!']
>>> reduce(lambda s, p: s.replace(p[0],p[1]),[subject]+zip(search, replace+['']*(len(search)-len(replace))))
'Making Python one-liners can be fun!'

回答by Glenn Maynard

Do it with regexps:

用正则表达式来做:

import re

def replace_from_list(replacements, str):
    def escape_string_to_regex(str):
        return re.sub(r"([\.^$*+?{}[\]|\(\)])", r"\", str)

    def get_replacement(match):
        return replacements[match.group(0)]

    replacements = dict(replacements)
    replace_from = [escape_string_to_regex(r) for r in replacements.keys()]
    regex = "|".join(["(%s)" % r for r in replace_from])
    repl = re.compile(regex)

    return repl.sub(get_replacement, str)

# Simple replacement:
assert replace_from_list([("in1", "out1")], "in1") == "out1"

# Replacements are never themselves replaced, even if later search strings match
# earlier destination strings:
assert replace_from_list([("1", "2"), ("2", "3")], "123") == "233"

# These are plain strings, not regexps:
assert replace_from_list([("...", "out")], "abc ...") == "abc out"

Using regexps for this makes the searching fast. This won't iteratively replace replacements with further replacements, which is usuallywhat's wanted.

为此使用正则表达式可以使搜索快速。这不会用进一步的替换迭代替换替换,这通常是我们想要的。

回答by Юки Эндо

Made a tiny recursive function for this

为此做了一个很小的递归函数

def str_replace(sbjct, srch, rplc):
    if len(sbjct) == 0:
        return ''

    if len(srch) == 1:
        return sbjct.replace(srch[0], rplc[0])

    lst = sbjct.split(srch[0])
    reslst = []
    for s in lst:
        reslst.append(str_replace(s, srch[1:], rplc[1:]))
    return rplc[0].join(reslst);