【问题标题】:Replace a character from a returned string of variable从返回的变量字符串中替换一个字符
【发布时间】:2020-06-19 06:52:34
【问题描述】:

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

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)

作为回报,我得到了这个

<re.Match object; span=(27, 34), match='2020_01'>
None

这是正确的。 我随后尝试了这个:

#Replace '_' with '-'
date = getdate.replace('_', '-')
print(date)

但它给了我一个错误

AttributeError: 'NoneType' object has no attribute 'replace'

有什么建议吗?从(getdate)返回的字符串不被识别吗?

另外,我如何将该字符串写入具有一些额外值的 .prm 文件,例如:

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

【问题讨论】:

    标签: python string file variables replace


    【解决方案1】:

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

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

    所以你需要先检查一下,你是否首先得到了结果:

    if getdate:
      date = getdate.group(0).replace('_', '-')
    

    所以检查你是否有“某物”(而不是“无”),而不是对某物进行操作。您也可以在documentation 中找到此模式。

    注意search 确实返回一个字符串。它返回一个Match 对象(或无)。您的正则表达式可以使用组来捕获多个事物,但在这种情况下,您只有一个,它位于第 0 组中。这将为您提供实际的字符串。

    【讨论】:

      猜你喜欢
      • 2017-11-17
      • 1970-01-01
      • 2020-07-09
      • 2014-03-13
      • 2020-03-30
      • 2013-02-16
      • 1970-01-01
      • 2020-02-04
      相关资源
      最近更新 更多