[英]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:几个问题:
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():
来迭代行。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.string_file
, not str
. string_file
,而不是str
。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.