Python 的sub和replace的区别 python replace正则怎么用

\u5982\u4f55\u7528python\u7684re.sub( )\u65b9\u6cd5\u8fdb\u884c\u201c\u591a\u5904\u201d\u66ff\u6362

\u6b63\u5219\u8868\u8fbe\u5f0f\u91cc \u6216 \u662f |
import res0 = 'BOY and GIRL's1 = re.sub(r'BOY|GIRL', 'HUMAN', s0)print s1# HUMAN and HUMAN

# encoding: UTF-8
import re
s="\u4eca\u5929\u662f2015\u5e7410\u67081\u65e5\u56fd\u5e86\u8282,\u660e\u5929\u662f2015\u5e7410\u67082\u65e5";
result = s.replace("2015\u5e7410\u67081\u65e5", "00") #\u53ea\u80fd\u7528\u4e8e\u5b57\u7b26\u4e32\u66ff\u6362
print result;

result, number = re.subn("\d+\u5e74\d+\u6708\d+\u65e5", "00", s) #\u53ef\u4ee5\u7528\u4e8e\u6b63\u5219\u7684\u66ff\u6362
print result;
print number;

sub出现于re库,用法是re.sub(pattern, repl, string, count=0, flags=0)
实例,re.sub(r'e','a','def',count = 1)
>>> daf
相对于replace来说,该方法功能更强,但是运行效率更低。
replace是自带函数,用法是str.replace(old, new[, max])
实例,'abbc'.replace('b','a',1)
>>>aabc
对比re.sub来说,replace没有正则的效果,但是运行效率更佳。请在实际应用中根据需求来定制使用方法,不要浪费资源。

你好:
sub是正则表达式,他的功能更加强大;
而replace知识一个替换;

inputStr = "hello 123 world 456"
而你想把123和456,都换成222,这时候replace就无能为力了!

举个具体点的例子?哪个类的sub和replace函数?

扩展阅读:python sub n digui ... sub在python中的用法 ... python re sub和replace ... python中strip 函数 ... pythonresub用法 ... python sub函数 ... 学python后到底能干什么 ... python手机版下载官方 ... python基础代码大全 ...

本站交流只代表网友个人观点,与本站立场无关
欢迎反馈与建议,请联系电邮
2024© 车视网