日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

python中快速進行多個字符替換的方法小結

系統 1759 0

先給出結論:

  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

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家學習或者使用python能有所幫在,如果有疑問大家可以留言交流。


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 泌阳县| 明溪县| 开阳县| 望都县| 云龙县| 措美县| 新泰市| 广平县| 阳山县| 军事| 阿坝| 永靖县| 吉木乃县| 自治县| 大名县| 陆良县| 新河县| 都江堰市| 旬邑县| 龙井市| 大化| 那曲县| 客服| 郁南县| 抚顺县| 绍兴县| 宣汉县| 乐东| 博客| 西盟| 郧西县| 呼伦贝尔市| 恩平市| 额敏县| 康平县| 庄浪县| 墨玉县| 佛坪县| 大化| 普宁市| 松江区|