Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/hadoop/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果字符串中的行以字符开头,Python将替换子字符串_Python_String_Text_Replace_Startswith - Fatal编程技术网

如果字符串中的行以字符开头,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)