Search code examples
pythonstringtextreplacestartswith

Python replace substring if line within string starts with character


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)

Solution

  • Several problems:

    1. 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.
    2. 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.
    3. The name of the function parameter should be string_file, not str.
    4. The function needs to return the new string, so you can assign that to a variable.
    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)