简体   繁体   English

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

[英]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.我有一个长的多行字符串,如果该行以某个字符开头,我想替换该行上的 substring。

In this case replace from where the line starts with --在这种情况下from该行的开头替换--

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.所以在这里它将仅替换第二行from 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:几个问题:

  1. for line in string_file: iterates over the characters, not the lines. for line in string_file:遍历字符,而不是行。 You can use for line in string_file.splitlines(): to iterate over lines.您可以使用for line in string_file.splitlines():来迭代行。
  2. lines.replace() doesn't modify the line in place, it returns a new line. lines.replace()不会修改该行,它会返回一个新行。 You need to assign that to something to produce your result.您需要将其分配给某些东西以产生结果。
  3. The name of the function parameter should be string_file , not str . function 参数的名称应该是string_file ,而不是str
  4. The function needs to return the new string, so you can assign that to a variable. function 需要返回新字符串,因此您可以将其分配给变量。
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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM