Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.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_File_Variables_Replace - Fatal编程技术网

Python 替换返回的变量字符串中的字符

Python 替换返回的变量字符串中的字符,python,string,file,variables,replace,Python,String,File,Variables,Replace,我正在尝试替换返回字符串的一个字符。 首先,我得到的字符串 import os import re #List .xlsx files followed by the string ESC filenames = os.listdir('//xxx.xxx.xxx.com//a//b//c//archive') for filename in filenames: getdate = re.search('(?<=ESC_)\w+', filename) print (g

我正在尝试替换返回字符串的一个字符。 首先,我得到的字符串

import os
import re

#List .xlsx files followed by the string ESC
filenames = os.listdir('//xxx.xxx.xxx.com//a//b//c//archive')
for filename in filenames:
    getdate = re.search('(?<=ESC_)\w+', filename)
    print (getdate)
但这给了我一个错误

AttributeError: 'NoneType' object has no attribute 'replace'
有什么建议吗?是否无法识别从(getdate)返回的字符串

另外,如何使用一些额外的值将该字符串写入.prm文件,如:

Body of .prm file has (date), aaaa, bbbb and cccc

因此,您包含的输出显示第一个文件名匹配,但第二个文件名不匹配。如果我们查看,我们会看到,如果存在匹配项,它将返回一个
Match
对象,如果没有匹配项,它将返回一个
None

是其他语言中python中的一个特殊值(如NULL),表示“nothing”。它根本没有
replace
方法!这正是错误所说的

因此,您需要首先检查,您是否在第一时间获得了结果:

if getdate:
  date = getdate.group(0).replace('_', '-')
因此,检查你是否有“某物”(与“无”相反),而不是对某物进行操作。您也可以在中找到此模式

请注意,
search
不会返回字符串。它返回一个
Match
对象(或无)。您的正则表达式可以使用组来捕获多个内容,但在本例中,您只有一个,即组0中的内容。这将得到实际的字符串

Body of .prm file has (date), aaaa, bbbb and cccc
if getdate:
  date = getdate.group(0).replace('_', '-')