【问题标题】:How to ignore whitespace in python如何忽略python中的空格
【发布时间】:2017-12-12 03:56:52
【问题描述】:

我正在尝试检查一个字符串,如果它存在,我不想写入文件,但字符串在它们之间的不同位置有空格,这使得它难以捕获。

示例文本:

this is test (enclosed ("further enclosed...
Line to be printed:1
this is test(enclosed ("further enclosed...
Line to be interpreted 
this is test(enclosed("further enclosed...
this is test (enclosed("further enclosed...

预期输出

Line to be printed:1
Line to be printed:2

我尝试了下面的代码,但它不起作用:

for word in words:
    if 'this is test .*(enclosed .*(\"' not in word :
        fw.write (word)

我正在将它写入文件。

有人可以帮助我如何实现预期的输出吗?如果您需要更多详细信息,请告诉我。另外,我不想使用类似

的内容
if 'this is test (enclosed (\"' not in word or 'this is test(enclosed(\"' not in word :

【问题讨论】:

  • not in 不会查找正则表达式。您必须明确使用正则表达式包。
  • 解决问题的两种方法:1)在模式中的任何地方放置可选空格(Neos07 方法)或 2)在使用更简单的模式(使用re.match)。我让你选择最合适的方法。
  • @CasimiretHippolyte 并使用正则表达式包 :)
  • 是的:使用re.search 而不是in。导入 re 不会将子字符串搜索转换为正则表达式搜索。
  • @Saurabh:import 语句不会向语言添加功能,但会从导入的模块中提供可用的方法。查看 re 模块手册页,了解哪些新方法可用以及如何使用它们。

标签: python regex removing-whitespace


【解决方案1】:

我认为问题不在于空格,但您没有转义括号。 对于空格,您可以使用 \s 而不是 . 所以你的正则表达式将是:

this is test\s*\(enclosed\s*\("

【讨论】:

  • 除了 OP 根本没有使用正则表达式
  • 但他在他的问题中使用了正则表达式标签。
  • @Neos07 :我尝试了您的解决方案。很遗憾。它没有工作
猜你喜欢
  • 2021-05-24
  • 1970-01-01
  • 2020-09-27
  • 1970-01-01
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
  • 2013-02-25
  • 2021-12-31
相关资源
最近更新 更多