本文介绍了python字符串搜索替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SSViewer::set_theme('bullsorbit');

这是我的字符串.我想在字符串 "SSViewer::set_theme('bullsorbit'); " 中搜索并将 'bullsorbit' 替换为另一个字符串.'bulllsorbit' 字符串是动态变化的.

this my string. I want search in string "SSViewer::set_theme('bullsorbit'); " and replace 'bullsorbit' with another string. 'bullsorbit' string is dynamically changing.

推荐答案

无法对此进行测试,因此您可能需要摆弄正则表达式(它们可能是其中的错误.)

Not in a situation to be able to test this so you may need to fiddle with the Regular Expression (they may be errors in it.)

import re
re.sub("SSViewer::set_theme\('[a-z]+'\)", "SSViewer::set_theme('whatever')", my_string)

这是你想要的吗?

刚刚测试过,这是一些示例输出:

Just tested it, this is some sample output:

my_string = """Some file with some other junk
SSViewer::set_theme('bullsorbit');
SSViewer::set_theme('another');
Something else"""

import re
replaced = re.sub("SSViewer::set_theme\('[a-z]+'\)", "SSViewer::set_theme('whatever')", my_string)
print replaced

产生:

Some file with some other junk
SSViewer::set_theme('whatever');
SSViewer::set_theme('whatever');
Something else

如果您想对文件执行此操作:

if you want to do it to a file:

my_string = open('myfile', 'r').read()

这篇关于python字符串搜索替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 00:59