str_replace() 对字符串进行批量或多次替换,类似PHP的str_replace()。
str_replace() 接收三个参数,第一个为要替换的字符串,第二个为要查找的字符串,第三个为替换后的新字符串。
以下是 str_replace() 的语法:
str_replace(find, old=[], new=None)
● find [str]:要替换的字符串。
● old [list]:要查找的字符串,必须是列表。
● new [list|str]:替换后的新字符串,可以是列表或字符。
返回替换后的字符串。
以下展示了使用 str_replace() 的实例:
from kyger.utility import str_replace print(str_replace('https://www.kg.cn', ['kg', 'cn'], ['kgcms', 'com'])) # 多换多 print(str_replace('[{"AGE": "15"}{"Age": "18"}]', ['AGE', 'Age'], 'age')) # 一换多
以上实例运行后输出的结果为:
'https://www.kgcms.com' '[{"age": "15"}{"age": "18"}]'