如果字符串中的行以字符开头,Python将替换子字符串
同样措辞的问题,但不是我想要的- 我有一个长的多行字符串,如果行以某个字符开头,我想替换行上的子字符串 在这种情况下,从替换如果字符串中的行以字符开头,Python将替换子字符串,python,string,text,replace,startswith,Python,String,Text,Replace,Startswith,同样措辞的问题,但不是我想要的- 我有一个长的多行字符串,如果行以某个字符开头,我想替换行上的子字符串 在这种情况下,从替换,其中行以-- 因此,这里它将仅替换中的第二行。像这样的- def substring_replace(str_file): for line in string_file: if line.startswith(' --'): line.replace('from','fromm') substring_replace
,其中行以--
因此,这里它将仅替换
中的第二行。像这样的-
def substring_replace(str_file):
for line in string_file:
if line.startswith(' --'):
line.replace('from','fromm')
substring_replace(string_file)
几个问题:
对于字符串文件中的行:
迭代字符,而不是行。您可以对string_文件中的行使用。splitlines():
来迭代行
lines.replace()
不会在位修改该行,而是返回新行。您需要将其分配给某个对象以产生结果
函数参数的名称应该是string\u file
,而不是str
函数需要返回新字符串,因此可以将其分配给变量
不要使用str
作为参数名,它会干扰Python类型名。而且您不能在适当的位置修改字符串,您需要从函数返回一个修改过的版本。谢谢您给出了这个清晰的答案
def substring_replace(str_file):
for line in string_file:
if line.startswith(' --'):
line.replace('from','fromm')
substring_replace(string_file)
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)