pythonで複数文字の置換を迅速に行う方法のまとめ
2061 ワード
まず結論を出します.置換する文字数が少ない場合、直接チェーン 置換する文字数が多い場合は、forループで
実行可能な方法:
1.チェーン式replace()
1.x
2.stringを使用する.maketrans
3.先re.そしてsub
……
参照リンク:
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を使ったりするのに役立つことを望んでいます.疑問があれば、伝言を残して交流してください.
replace()
方法で置換することができ、効率が非常に高い.replace()
を呼び出して置換することを推奨します.実行可能な方法:
1.チェーン式replace()
string.replace().replace()
1.x
for
サイクルでreplace()
「置換する文字が多い場合」を呼び出す2.stringを使用する.maketrans
3.先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を使ったりするのに役立つことを望んでいます.疑問があれば、伝言を残して交流してください.