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)
Several problems:
for line in string_file:
iterates over the characters, not the lines. You can use for line in string_file.splitlines():
to iterate over lines.lines.replace()
doesn't modify the line in place, it returns a new line. You need to assign that to something to produce your result.string_file
, not str
.def substring_replace(string_file):
result = []
for line in string_file.splitlines():
if line.startswith('-- '):
line = line.replace('from', 'fromm')
result.append(line)
return '\n'.join(result)
string_file = substring_replace(string_file)