Best way to replace multiple characters in a string?

前端 未结 14 2077
遇见更好的自我
遇见更好的自我 2020-11-22 11:15

I need to replace some characters as follows: &\\&, #\\#, ...

I coded as follows, but I guess there

14条回答
  •  醉话见心
    2020-11-22 11:46

    FYI, this is of little or no use to the OP but it may be of use to other readers (please do not downvote, I'm aware of this).

    As a somewhat ridiculous but interesting exercise, wanted to see if I could use python functional programming to replace multiple chars. I'm pretty sure this does NOT beat just calling replace() twice. And if performance was an issue, you could easily beat this in rust, C, julia, perl, java, javascript and maybe even awk. It uses an external 'helpers' package called pytoolz, accelerated via cython (cytoolz, it's a pypi package).

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

    I'm not even going to explain this because no one would bother using this to accomplish multiple replace. Nevertheless, I felt somewhat accomplished in doing this and thought it might inspire other readers or win a code obfuscation contest.

提交回复
热议问题