Fastest implementation to do multiple string substitutions in Python

后端 未结 3 525
攒了一身酷
攒了一身酷 2020-12-14 23:30

Is there any recommended way to do multiple string substitutions other than doing replace chaining on a string (i.e. text.replace(a, b).replace(c, d).repl

3条回答
  •  生来不讨喜
    2020-12-15 00:04

    How fast? Also, how big are your strings?

    There's a fairly simple recipe for building a regular expression to do the job on another site. It might need some tweaking to handle regex metacharacters; I didn't look too closely.

    If that's not good enough, you probably need to write some C code, honestly. You can build a simple state machine to do all the replacements, and then process any string byte by byte with no backtracking along the machine to actually do the work. However, I doubt you will beat the regex engine without going to C and optimizing that.

提交回复
热议问题