s = """Comment=This is a comment
Name=Frank J. Lapidus
GenericName=Some name"""
replace_name = "Dr. Jack Shephard"
I have some text in a file and have been trying to figure out how to search and replace a line so Name=Frank J. Lapidus becomes Name=Dr. Jack Shephard
How could I do this in Python? Edited: (BTW, the second element would be a \n just in case you were wondering).
Thanks.
You could use the regular expression functions from the re module. For example like this:
(The
re.MULTILINEoption makes^and$match the beginning and the end of a line, respectively, in addition to the beginning and the end of the string.)Edited to add: Based on your comments to Emil’s answer, it seems you are manipulating Desktop Entry files. Their syntax seems to be quite close to that used by the ConfigParser module (perhaps some differences in the case-sensitivity of section names, and the expectation that comments should be preserved across a parse/serialize cycle).
An example: