0

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)
1
  • 1
    Don't use str as 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. Commented Mar 23, 2021 at 20:10

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.