python - 使用 Python 搜索字符串

标签 python

我有以下句子:

Dave put the rubbish in the {{ if dave_good }}bin{{ else }}street{{ endif }}.

我目前正在通过捕获 [[ something ]] 来替换文本字符串中的变量并将整个实例替换为值(不是问题)。但这是使用 python 的 re图书馆。

我想知道是否有人可以告诉我如何:

  1. 搜索 {{ if dave_good }} 的单个实例在字符串中
  2. {{ if dave_good }} 向前计数确保有 {{ endif }}在字符串末尾之前
  3. 如果没有{{ else }}然后根据dave_good的 bool 属性删除标签,或标签及其内容(在文本中的位置)
  4. 如果有{{ else }}
    1. 如果 dave_goodTRUE然后删除 {{ if dav_good }}{{ else }}street{{ endif}}
    2. 如果 dave_goodFALSE然后删除 {{ endif }}{{ if dave_good }}bin{{ else }}

最佳答案

尝试使用Regular Expressions .

示例:

import re

result = re.match("\{\{((if|else|endif).*?)\}\}","{{if 100 > 1}}",re.I)
print result.groups()

result = re.match("\{\{((if|else|endif).*?)\}\}","{{else}}",re.I)
print result.groups()

result = re.match("\{\{((if|else|endif).*?)\}\}","{{endif}}",re.I)
print result.groups()

或者使用Python的模板引擎

  1. jinja
  2. cheetah
  3. Templating
  4. bottlepy

祝你好运!

关于python - 使用 Python 搜索字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19772750/

相关文章:

python - 在 python 中使用 CSV 文件数据绘制热图

python - 组织一个大型 python 脚本

python - django tastypie 和 xml 错误消息 : Please check your `` formats `` and ` `content_types`` on your Serializer

python - 使用递归或迭代方法在 Python 中构建嵌套的树状结构

python - 如何压缩两个不同大小的列表?

python - 按换行符通配符反斜杠分割

python - 连接两个一维 NumPy 数组

python - 如何在 Django ORM 中获取常量列?

python - 提取字符串中的列表或元组

Python boto3 过滤RDS标签