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

Python replace substring if line within string starts with character

措辞相似的问题,但不是我要找的 -

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

在这种情况下,将行以 --

开头的地方替换为 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() 没有修改行,它 return 是一个新行。您需要将其分配给某些东西才能产生结果。
  3. 函数参数的名称应该是string_file,而不是str
  4. 该函数需要 return 新字符串,因此您可以将其分配给变量。
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)