python中快速进行多个字符替换的方法小结

作者:daisy 时间:2021-08-19 05:59:34 

先给出结论:

  1. 要替换的字符数量不多时,可以直接链式replace()方法进行替换,效率非常高;

  2. 如果要替换的字符数量较多,则推荐在 for 循环中调用 replace() 进行替换。

可行的方法:

1. 链式replace()


string.replace().replace()

     1.x 在for循环中调用replace() 「在要替换的字符较多时」

2. 使用string.maketrans

3. 先 re.compile 然后 re.sub

……


def a(text):
chars = "&#"
for c in chars:
text = text.replace(c, "\\" + c)
def b(text):
for ch in ['&','#']:
if ch in text:
 text = text.replace(ch,"\\"+ch)
import re
def c(text):
rx = re.compile('([&#])')
text = rx.sub(r'\\\1', text)
RX = re.compile('([&#])')
def d(text):
text = RX.sub(r'\\\1', text)
def mk_esc(esc_chars):
return lambda s: ''.join(['\\' + c if c in esc_chars else c for c in s])
esc = mk_esc('&#')
def e(text):
esc(text)
def f(text):
text = text.replace('&', '\&').replace('#', '\#')
def g(text):
replacements = {"&": "\&", "#": "\#"}
text = "".join([replacements.get(c, c) for c in text])
def h(text):
text = text.replace('&', r'\&')
text = text.replace('#', r'\#')
def i(text):
text = text.replace('&', r'\&').replace('#', r'\#')

参考链接:

http://stackoverflow.com/questions/3411771/multiple-character-replace-with-python

http://stackoverflow.com/questions/6116978/python-replace-multiple-strings

http://stackoverflow.com/questions/8687018/python-string-replace-two-things-at-once

http://stackoverflow.com/questions/28775049/most-efficient-way-to-replace-multiple-characters-in-a-string

来源:http://crazyof.me/blog/archives/3051.html?utm_source=tuicool&utm_medium=referral

标签:python,字符串
0
投稿

猜你喜欢

  • php 常用算法和时间复杂度

    2023-11-05 10:30:49
  • Django在pycharm下修改默认启动端口的方法

    2023-09-27 09:04:07
  • 解决Pycharm运行时找不到文件的问题

    2023-06-15 00:26:39
  • Python subprocess模块功能与常见用法实例详解

    2021-08-30 02:46:43
  • python实现sm2和sm4国密(国家商用密码)算法的示例

    2021-11-17 08:02:13
  • Python做图像处理及视频音频文件分离和合成功能

    2022-07-31 14:58:05
  • tensorflow可视化Keras框架中Tensorboard使用示例

    2023-08-09 01:39:27
  • Python远程桌面协议RDPY安装使用介绍

    2023-11-06 05:37:23
  • pytorch超详细安装教程之Anaconda、PyTorch和PyCharm全套安装流程

    2023-12-23 15:27:50
  • Python爬取你好李焕英豆瓣短评生成词云的示例代码

    2021-04-06 12:13:21
  • 安装MySQL错误归档处理

    2008-12-22 14:50:00
  • RDFa介绍——构建更友好的web页面

    2009-09-19 17:01:00
  • go Cobra命令行工具入门教程

    2023-06-24 18:27:12
  • python贪吃蛇游戏代码

    2023-07-22 04:19:17
  • Python中input()函数的用法实例小结

    2021-09-04 18:42:59
  • 如何使用python3获取当前路径及os.path.dirname的使用

    2023-07-22 06:29:37
  • Python参数解析模块sys、getopt、argparse使用与对比分析

    2021-12-19 17:39:58
  • Python无权点文件转化成邻接矩阵方式

    2021-04-19 02:14:29
  • JavaScript的事件代理比你想的要简单

    2009-04-27 12:40:00
  • CentOS 5.5使用yum来安装LAMP(php运行环境)

    2023-11-14 12:15:52
  • asp之家 网络编程 m.aspxhome.com