python string search replace

前端 未结 4 1235
陌清茗
陌清茗 2021-01-22 20:25
SSViewer::set_theme(\'bullsorbit\'); 

this my string. I want search in string \"SSViewer::set_theme(\'bullsorbit\'); \" and replace

4条回答
  •  天命终不由人
    2021-01-22 20:46

    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)
    

    Is this what you want?

    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
    

    produces:

    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()
    

提交回复
热议问题