Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

同時置換字串中的多種特定內容 #1

Open
scrum-1 opened this issue Apr 29, 2019 · 0 comments
Open

同時置換字串中的多種特定內容 #1

scrum-1 opened this issue Apr 29, 2019 · 0 comments

Comments

@scrum-1
Copy link
Owner

scrum-1 commented Apr 29, 2019

搜尋過程, 以"python replace different string simultaneously" 作為關鍵字, 參考 https://stackoverflow.com/questions/6116978/how-to-replace-multiple-substrings-of-a-string/6117042 中所提供的方法, 可以同時將 config/content.htm 中的 h 各往後推送一階.

import re

rep = {"h1": "h2", "h2": "h3", "h3": "h4"} # define desired replacements here

# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.items())
pattern = re.compile("|".join(rep.keys()))

#text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)

result = pattern.sub(lambda m: rep[re.escape(m.group(0))], "<h1>test1</h1>test1<h2>test2</h2>test2<h3>test3</h3>test3")
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant