我需要替换一些字符如下:&➔\&,#➔\#,…

我的编码如下,但我想应该有更好的方法。有提示吗?

strs = strs.replace('&', '\&')
strs = strs.replace('#', '\#')
...

当前回答

仅供参考,这对OP没有什么用处,但对其他读者可能有用(请不要投反对票,我知道这一点)。

作为一个有点荒谬但有趣的练习,我想看看是否可以使用python函数式编程来替换多个字符。我很确定这并不比调用replace()两次好。如果性能是个问题,你可以用rust、C、julia、perl、java、javascript甚至awk轻松解决。它使用一个名为pytoolz的外部“助手”包,通过cython加速(cytoolz,它是一个pypi包)。

from cytoolz.functoolz import compose
from cytoolz.itertoolz import chain,sliding_window
from itertools import starmap,imap,ifilter
from operator import itemgetter,contains
text='&hello#hi&yo&'
char_index_iter=compose(partial(imap, itemgetter(0)), partial(ifilter, compose(partial(contains, '#&'), itemgetter(1))), enumerate)
print '\\'.join(imap(text.__getitem__, starmap(slice, sliding_window(2, chain((0,), char_index_iter(text), (len(text),))))))

我甚至不打算解释这一点,因为没有人会使用它来完成多次替换。尽管如此,我还是觉得这样做有点成就感,并认为它可能会激励其他读者,或者赢得一场代码混淆竞赛。

其他回答

你总是要在反斜杠前加引号吗?如果是,试试

import re
rx = re.compile('([&#])')
#                  ^^ fill in the characters here.
strs = rx.sub('\\\\\\1', strs)

这可能不是最有效的方法,但我认为这是最简单的方法。

>>> string="abc&def#ghi"
>>> for ch in ['&','#']:
...   if ch in string:
...      string=string.replace(ch,"\\"+ch)
...
>>> print string
abc\&def\#ghi

这将帮助人们找到一个简单的解决方案。

def replacemany(our_str, to_be_replaced:tuple, replace_with:str):
    for nextchar in to_be_replaced:
        our_str = our_str.replace(nextchar, replace_with)
    return our_str

os = 'the rain in spain falls mainly on the plain ttttttttt sssssssssss nnnnnnnnnn'
tbr = ('a','t','s','n')
rw = ''

print(replacemany(os,tbr,rw))

输出:

他是我的家人他的pli

像这样简单地连接替换函数

strs = "abc&def#ghi"
print strs.replace('&', '\&').replace('#', '\#')
# abc\&def\#ghi

如果替换的数量更多,你可以用这种通用的方法

strs, replacements = "abc&def#ghi", {"&": "\&", "#": "\#"}
print "".join([replacements.get(c, c) for c in strs])
# abc\&def\#ghi

使用在python2.7和python3中可用的reduce。你可以用简洁的python方式替换多个子字符串。

# Lets define a helper method to make it easy to use
def replacer(text, replacements):
    return reduce(
        lambda text, ptuple: text.replace(ptuple[0], ptuple[1]), 
        replacements, text
    )

if __name__ == '__main__':
    uncleaned_str = "abc&def#ghi"
    cleaned_str = replacer(uncleaned_str, [("&","\&"),("#","\#")])
    print(cleaned_str) # "abc\&def\#ghi"

在python2.7中,你不需要导入reduce,但在python3中。你必须从functools模块中导入它。