python有什么便捷的替换方式吗?
现在有一个文本,有近50个字符串需要替换,有便捷的替换方法吗?
不用循环replace
用正则表达式的re.sub()函数
import re
new_text = re.sub('old', 'new', text)
用字符串的replace()方法和字典
replacements = {'old1': 'new1', 'old2': 'new2', ...}
for old, new in replacements.items():
text = text.replace(old, new)
用字符串的translate()方法和str.maketrans()函数
replacements = {'old1': 'new1', 'old2': 'new2', ...}
translation_table = str.maketrans(replacements)
new_text = text.translate(translation_table)
循环replace就是便捷方法呀,你自己循环比较不是更麻烦
想简化可以用列表推导式或者map代替循环,但是底层其实还是循环
用re
使用正则表达式进行替换
import re
text = "The quick brown fox jumps over the lazy dog."
new_text = re.sub("fox", "cat", text)
print(new_text)
输出:
The quick brown cat jumps over the lazy dog.
正则表达式:比如
import re
text = "Hello, world! How are you today?"
new_text = re.sub(r"world", "Python", text)
print(new_text)