Reputation: 29
I am a beginner. This seems so simple, but I have spent hours searching and trying different things with no luck. I want to express the string I am compiling as a variable.
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)
In my program card is constantly changing. How do I do this?
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'
Upvotes: 1
Views: 2884
Reputation: 8938
The problem in your second example is that you assign ['4c']
(a list) to card
rather than "['4c']"
(the string that works in your first example). re.compile
expects a string pattern.
Adjust as follows, and your second example will work like your first example:
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
Having said this, the pattern "['4c']"
seems suspect. At minimum, '
is redundant within the regex character set (bounded by the opening [
and the closing ]
): make sure card
is a string that specifies a sensible regex pattern for your needs.
Upvotes: 2
Reputation: 4139
There are at least two mistakes in your program
First, a strange Regex wildcard
You suppose to read at least a basic regex before you using it, you explicitly misunderstand it, here some useful cheat sheet and manual.
['4c']
(wrong! it stands for either one character '
, 4
or c
but there is duplicated '
)
['4c]
(right! it stands for either one character '
, 4
or c
),
[4c']
(right! it stands for either one character '
, 4
or c
),
[4c]
(right! it stands for either one character 4
or c
)
Second, Python list != Regex wildcard
['4c']
is a list which contains string '4c'
,
"['4c']"
is a string which contain regular expression wildcard.
Finally, if you prefer to use the second form of your code, your code suppose to look like this
card = "['4c']" # not clear here what you want to do
p = re.compile(card)
for m in p.finditer('234567891JQKA'):
q = str(m.start() + 2)
Upvotes: 1