python - 如何在Python中重新编译变量?

标签 python regex

我是初学者。这看起来很简单,但我花了几个小时搜索并尝试不同的东西,但没有运气。我想将我正在编译的字符串表示为变量。

所以这有效:

p = re.compile("['4c']")

for m in p.finditer('234567891JQKA'):
    q = str(m.start() + 2)

虽然这不会:

card = ['4c']
p = re.compile(card)

for m in p.finditer('234567891JQKA'):
    q = str(m.start() + 2)

我的程序卡在不断变化。我该怎么做?

我得到的错误是:

File "C:\Python34\lib\re.py", line 223, in compile
return _compile(pattern, flags)
File "C:\Python34\lib\re.py", line 282, in _compile
p, loc = _cache[type(pattern), pattern, flags]
TypeError: unhashable type: 'list'

最佳答案

第二个示例中的问题是您将 ['4c'] (列表)分配给 card 而不是 “['4c']”(在第一个示例中起作用的字符串)。 re.compile 需要一个字符串模式。

按如下方式进行调整,您的第二个示例将像第一个示例一样工作:

import re # added for clarity

card = "['4c']"
#      ^      ^
p = re.compile(card)

# or

card = ['4c']
p = re.compile(str(card))  # str(card) == "['4c']"
#              ^^^^    ^

for m in p.finditer('234567891JQKA'):
    q = str(m.start() + 2)
    # added for clarity
    print m.start()  # prints 2
    print q          # prints 4

话虽如此,模式“['4c']”似乎很可疑。至少,'regex character set 中是多余的(以开始的 [ 和结束的 ] 为界):确保 card 是一个字符串,它根据您的需要指定合理的正则表达式模式。

关于python - 如何在Python中重新编译变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32418209/

相关文章:

python - Pandas df.to_csv ("file.csv"encode ="utf-8")仍然为减号提供垃圾字符

python - 将 Auth 烘焙到 Azure 函数应用程序中 : what's the canonical way?

python - 痛饮 : function that modifies its argument from c++ to python

javascript - Django 不断检查数据库中的新信息

python - 为什么我无法导入 ABC,但 ABCMeta 却正确导入?

python - python 中的字符串与正则表达式比较在 python 中失败

regex - htaccess 删除 .php、.html 和尾部斜杠

javascript - 将适用于 php 的 REGEX 转换为 Javascript

java - 分割一个没有与java中的正则表达式匹配的相邻字符的字符串

java - 在java中获取匹配的正则表达式