python string search replace

前端 未结 4 1192
陌清茗
陌清茗 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:45
    st = "SSViewer::set_theme('"
    for line in open("file.txt"):
        line=line.strip()
        if st in line:
            a = line[ :line.index(st)+len(st)]
            b = line [line.index(st)+len(st): ]
            i = b.index("')")
            b = b[i:]
            print a + "newword" + b
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
  • 2021-01-22 20:52
    >> my_string = "SSViewer::set_theme('bullsorbit');"
    >>> import re
    >>> change = re.findall(r"SSViewer::set_theme\('(\w*)'\);",my_string)
    >>> my_string.replace(change[0],"blah")
    "SSViewer::set_theme('blah');"
    

    its not elegant but it works. the findall will return a dictionary of items that are inside the ('') and then replaces them. If you can get sub to work then that may look nicer but this will definitely work

    0 讨论(0)
  • 2021-01-22 21:07

    while your explanation is not entirely clear, I think you might make some use of the following:

    open(fname).read().replace('bullsorbit', 'new_string')
    
    0 讨论(0)
提交回复
热议问题