如果字符串中的行以字符开头,则 Python 替换子字符串

问题描述

措辞类似的问题,但不是我想要的 -

我有一个很长的多行字符串,如果该行以某个字符开头,我想替换该行上的一个子字符串。

在这种情况下,替换以 from 开头的行的 --

string_file = 
'words more words from to cow dog
-- words more words from to cat hot dog
words more words words words'

所以这里它只会替换第二行 from。像这样 -

def substring_replace(str_file):
    for line in string_file: 
        if line.startswith(' --'):  
            line.replace('from','fromm')
substring_replace(string_file)

解决方法

几个问题:

  1. for line in string_file: 迭代字符,而不是行。您可以使用 for line in string_file.splitlines(): 遍历行。
  2. lines.replace() 不会就地修改该行,而是返回一个新行。您需要将其分配给某些东西以产生结果。
  3. 函数参数的名称应该是string_file,而不是str
  4. 该函数需要返回新字符串,因此您可以将其分配给一个变量。
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)