Similarly worded questions, but not quite what I'm looking for -
I have a long, multi-line string where I'd like to replace a substring on the line if the line starts with a certain character.
In this case replace from where the line starts with --
string_file =
'words more words from to cow dog
-- words more words from to cat hot dog
words more words words words'
So here it would replace the second line from only. Something like this -
def substring_replace(str_file):
for line in string_file:
if line.startswith(' --'):
line.replace('from','fromm')
substring_replace(string_file)
stras a parameter name, it interferes with the Python type name. And you can't modify the string in-place, you need to return a modified version from the function.