结论

先说结果, 直接替换是最好的. replace 一层层用, 方法笨了一点, 还可以.

懒得打字, 贴代码就完事了.

基准测试1

from cProfile import run

s = '1 a  2 \n \t \r e34234'

def _replace():
for x in range(5000000):
old_value2 = s.replace('\t', '')
old_value3 = old_value2.replace('\n', '')
old_value3.replace('\r', '') def _replace3():
for x in range(5000000):
old_value2 = s.replace('\t', '\\t')
old_value3 = old_value2.replace('\n', '\\n')
old_value3.replace('\r', '\\r') def _translate1():
for x in range(5000000):
s.translate(str.maketrans({'\t': '', '\n': '', '\r': ''})) t2 = str.maketrans({'\t': '', '\n': '', '\r': ''})
t3 = str.maketrans({'\t': None, '\n': None, '\r': None})
t4 = str.maketrans({'\t': '\\t', '\n': '\\n', '\r': '\\r'}) def _translate2():
for x in range(5000000):
s.translate(t2) def _translate3():
for x in range(5000000):
s.translate(t3) def _translate4():
for x in range(5000000):
s.translate(t4) print('### replace')
run("_replace()")
print('### replace3')
run("_replace3()")
print('### translate1')
run("_translate1()")
print('### translate2')
run("_translate2()")
print('### translate3')
run("_translate3()")
print('### translate4')
run("_translate4()")

速度: _replace > translate3 > _replace3 > translate2 > translate1 > translate4

结论: translate是个辣鸡~~

运行结果:

### replace
15000004 function calls in 4.451 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 4.451 4.451 <string>:1(<module>)
1 1.721 1.721 4.451 4.451 demo.py:7(_replace)
1 0.000 0.000 4.451 4.451 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
15000000 2.730 0.000 2.730 0.000 {method 'replace' of 'str' objects} ### replace3
15000004 function calls in 4.785 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 4.785 4.785 <string>:1(<module>)
1 1.830 1.830 4.785 4.785 demo.py:14(_replace3)
1 0.000 0.000 4.785 4.785 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
15000000 2.956 0.000 2.956 0.000 {method 'replace' of 'str' objects} ### translate1
10000004 function calls in 7.741 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 7.741 7.741 <string>:1(<module>)
1 1.870 1.870 7.741 7.741 demo.py:21(_translate1)
1 0.000 0.000 7.741 7.741 {built-in method builtins.exec}
5000000 1.052 0.000 1.052 0.000 {built-in method maketrans}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000000 4.819 0.000 4.819 0.000 {method 'translate' of 'str' objects} ### translate2
5000004 function calls in 5.284 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 5.284 5.284 <string>:1(<module>)
1 0.702 0.702 5.284 5.284 demo.py:31(_translate2)
1 0.000 0.000 5.284 5.284 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000000 4.582 0.000 4.582 0.000 {method 'translate' of 'str' objects} ### translate3
5000004 function calls in 3.548 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 3.548 3.548 <string>:1(<module>)
1 0.720 0.720 3.548 3.548 demo.py:36(_translate3)
1 0.000 0.000 3.548 3.548 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000000 2.828 0.000 2.828 0.000 {method 'translate' of 'str' objects} ### translate4
5000004 function calls in 5.751 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 5.751 5.751 <string>:1(<module>)
1 0.722 0.722 5.751 5.751 demo.py:41(_translate4)
1 0.000 0.000 5.751 5.751 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
5000000 5.029 0.000 5.029 0.000 {method 'translate' of 'str' objects}

基准测试2

时间消耗:

  • tx2 < tx3 < tx1 < tx4
  • t2 < t3 < t1 < t4

a = '你好的\r\n打分a\r\tdeadaaes\r\n\tttttrb' k = ('\r', '\n', '\t') def t1(text):
for ch in k:
if ch in text:
text = text.replace(ch, ' ')
return text def t2(old_value1):
# data reformat
old_value2 = old_value1.replace('\t', ' ')
old_value3 = old_value2.replace('\n', ' ')
return old_value3.replace('\r', ' ') def t3(old_value):
# data reformat
old_value = old_value.replace('\t', ' ')
old_value = old_value.replace('\n', ' ')
return old_value.replace('\r', ' ') def t3_1(old_value):
# data reformat
return old_value.replace('\r', ' ').replace('\t', ' ').replace('\n', ' ') def t4(s):
t = s.maketrans("\n\t\r", " ")
return s.translate(t) def tx1(x):
for i in range(0, 100000):
t1(x) def tx2(x):
for i in range(0, 100000):
t2(x) def tx3(x):
for i in range(0, 100000):
t3(x) def tx3_1(x):
for i in range(0, 100000):
t3_1(x) def tx4(x):
for i in range(0, 100000):
t4(x) tx1(a)
tx2(a)
tx3(a)
tx3_1(a)
tx4(a)

Profile:

https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string

Python 字符串多替换时性能基准测试的更多相关文章

  1. python字符串内容替换的方法(转载)

    python字符串内容替换的方法 时间:2016-03-10 06:30:46来源:网络 导读:python字符串内容替换的方法,包括单个字符替换,使用re正则匹配进行字符串模式查找与替换的方法.   ...

  2. Python - 字符串的替换(interpolation) 具体解释

    字符串的插值(interpolation) 具体解释 本文地址: http://blog.csdn.net/caroline_wendy/article/details/27054263 字符串的替换 ...

  3. python 字符串中替换字符

    今天本来打算写个程序,替换字符串中固定的一个字符:将<全部替换成回车'\n' 于是,我写成这样 s='sdjj<ddd<denj,>' for x in s: if x=='& ...

  4. python字符串replace失效问题

    python字符串replace替换无效 背景 今天想把一个列表中符合条件的元素中 替换部分字符串, 发现怎么替换,改元素还是没有改变,本以为是内存引用的问题后来发现并不然. 经查阅解决 在Pytho ...

  5. StackOverFlow排错翻译 - Python字符串替换: How do I replace everything between two strings without replacing the strings?

    StackOverFlow排错翻译 - Python字符串替换: How do I replace everything between two strings without replacing t ...

  6. Python - 字符串模板的安全替换(safe_substitute) 具体解释

    字符串模板的安全替换(safe_substitute) 具体解释 本文地址: http://blog.csdn.net/caroline_wendy/article/details/27057339 ...

  7. Python 字符串_python 字符串截取_python 字符串替换_python 字符串连接

    Python 字符串_python 字符串截取_python 字符串替换_python 字符串连接 字符串是Python中最常用的数据类型.我们可以使用引号('或")来创建字符串. 创建字符 ...

  8. python 字符串替换

    字符串替换可以用内置的方法和正则表达式完成.1用字符串本身的replace方法: a = 'hello word'b = a.replace('word','python')print b 2用正则表 ...

  9. python字符串替换的2种有效方法

    python 字符串替换可以用2种方法实现:1是用字符串本身的方法.2用正则来替换字符串 下面用个例子来实验下:a = 'hello word'我把a字符串里的word替换为python1用字符串本身 ...

随机推荐

  1. LNK2001 无法解析的外部符号 __imp__CameraCreateSettingPage@24

    用VS2017,Release X86进行编译时显示如下错误: 1>CWDMDlg.obj : error LNK2001: 无法解析的外部符号 __imp__CameraGetImageBuf ...

  2. luoguP2882Face The Right Way

    https://www.luogu.org/problem/P2882 题意 你有n头牛,每头牛有个朝向,你每次可以选择连续k头牛翻转,求k为多少时可以用最少的步骤将所有牛朝向变为正向 n≤5000 ...

  3. 基于 webdriver 的测试代码日常调试方python 篇

    看到论坛有人写了JAVA的测试代码日常设计,就给大家分享一下偶自己平时是如何测试测试代码的.主要基于python语言.基于 webdriver 的日常调试在 python交互模式下非常方便,打开pyt ...

  4. 【转】机器学习实战之K-Means算法

    一,引言 先说个K-means算法很高大上的用处,来开始新的算法学习.我们都知道每一届的美国总统大选,那叫一个竞争激烈.可以说,谁拿到了各个州尽可能多的选票,谁选举获胜的几率就会非常大.有人会说,这跟 ...

  5. VMWARE在UEFI下启动PE.ISO

    1.编辑虚拟机设置→选项→高级→通过EFI而非BIOS引导勾选. 2.虚拟机→电源→打开电源时进入固件,进入之后修改光驱为第一引导. 3.挂载PE.ISO,启动时虚拟机顶部出现Press any ke ...

  6. Linux性能优化实战学习笔记:第十七讲

    一.缓存命中率 1.引子 1.我们想利用缓存来提升程序的运行效率,应该怎么评估这个效果呢? 用衡量缓存好坏的指标 2.有没有哪个指标可以衡量缓存使用的好坏呢? 缓存命中率 3.什么是缓存命中率? 所谓 ...

  7. [LeetCode] 902. Numbers At Most N Given Digit Set 最大为 N 的数字组合

    We have a sorted set of digits D, a non-empty subset of {'1','2','3','4','5','6','7','8','9'}.  (Not ...

  8. [LeetCode] 234. Palindrome Linked List 回文链表

    Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false ...

  9. 初探Java设计模式4:一文带你掌握JDK中的设计模式

    转自https://javadoop.com/post/design-pattern 行为型模式 策略模式 观察者模式 责任链模式 模板方法模式 状态模式 行为型模式总结 本系列文章将整理到我在Git ...

  10. 推荐一款健康App 多喝水,引领全民时尚喝水生活习惯

    推荐一款健康App 多喝水,引领全民时尚喝水生活习惯 1 介绍 多喝水,一款鼓励大众喝水的APP.我们倡导大众健康生活,培养人们爱喝水的习惯,让每一次喝水,都能产生价值,让人们在喝水的同时,可享受赚钱 ...