【问题标题】:String Matching: Only first iteration match is caught字符串匹配:仅捕获第一次迭代匹配
【发布时间】:2014-06-29 22:33:42
【问题描述】:

我正在尝试在 Python 中创建一个小的迭代字符串匹配函数。当第一组匹配字符串被捕获时,我被难住了,但第二组匹配字符串没有。我添加了一个字符串转换以确保对象是字符串。我也理解 == 运算符匹配值,而不是对象。 (如果我的术语有误,请纠正我)。任何帮助将不胜感激。

#!/usr/bin/python


import re


NameLG_file = open("Name2.txt", "r")
NameSM_file = open("Inc2.txt", "r")
SMList = []
LGList = []


# Assign LG to List and Format
for a in NameLG_file:
    a = a.strip('\n')
    a = a.replace('\"', '')
    a = str(a)
    LGList.extend([a])


# Assign SM to list and format
for c in NameSM_file:
    c = c.strip('\n')
    c = str(c)
    SMList.extend([c])


# Identify and list orphans.
for e in LGList:
    for f in SMList:
        if e == f:
            print True
            print e
            print f
            print ""
            # break
        else:
            print False
            print e
            print f
            print ""

NameLG_file.close()
NameSM_file.close()

Name2.txt 包含

"teardown"
"Elite"
Binary

Inc2.txt 包含

teardown
Elite

输出是:

True
teardown
teardown

False
teardown
Elite

False
Elite
teardown

False
Elite
Elite

False
Binary
teardown

False
Binary
Elite

因此,我希望匹配的 Elite 字符串显示为 True。提前致谢!

【问题讨论】:

  • 你导入了re 但从不使用它;你是故意的吗?
  • 我不是,请忽略。

标签: python regex string


【解决方案1】:

在我看来,问题在于您的文件使用 Windows EOL (\r\n) 因此,当您执行 a.strip('\n') 时,返回的值为 "Elite\r" 而不是 "Elite"

解决办法是用strip()代替strip('\n')

【讨论】:

  • 太棒了!那行得通。不过我有点担心,strip() 是不是只去掉了回车?
  • 它会删除所有的withespaces,您可以在官方文档中找到信息:link
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 2015-07-16
  • 2014-08-15
  • 2013-07-07
相关资源
最近更新 更多