I am using Python 2.6 and am getting [what I think is] unexpected output from re.sub()
我正在使用Python 2.6并从re.sub()获得[我认为]的意外输出
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat')
'th- c-t s-t -n th- m-t'
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat', re.IGNORECASE)
'th- c-t sat on the mat'
If this output is what is expected, what is the logic behind it?
如果这个输出是预期的,它背后的逻辑是什么?
3 个解决方案
#1
Yes, the fourth parameter is count, not flags. You're telling it to apply the pattern twice (re.IGNORECASE = 2).
是的,第四个参数是count,而不是flags。你告诉它应用模式两次(re.IGNORECASE = 2)。
#2
To pass flags you can use re.compile
要传递标记,可以使用re.compile
expression = re.compile('[aeiou]', re.IGNORECASE)
expression.sub('-', 'the cat sat on the mat')
#3
In case you've upgraded since asking this question. If you are using Python 2.7+, you don't need to use re.compile
. You can call sub
and specify flags
with a named argument.
如果你问这个问题后你已经升级了。如果您使用的是Python 2.7+,则无需使用re.compile。您可以调用sub并使用命名参数指定标志。
>>> import re
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat', flags=re.IGNORECASE)
'th- c-t s-t -n th- m-t'
#1
Yes, the fourth parameter is count, not flags. You're telling it to apply the pattern twice (re.IGNORECASE = 2).
是的,第四个参数是count,而不是flags。你告诉它应用模式两次(re.IGNORECASE = 2)。
#2
To pass flags you can use re.compile
要传递标记,可以使用re.compile
expression = re.compile('[aeiou]', re.IGNORECASE)
expression.sub('-', 'the cat sat on the mat')
#3
In case you've upgraded since asking this question. If you are using Python 2.7+, you don't need to use re.compile
. You can call sub
and specify flags
with a named argument.
如果你问这个问题后你已经升级了。如果您使用的是Python 2.7+,则无需使用re.compile。您可以调用sub并使用命名参数指定标志。
>>> import re
>>> re.sub('[aeiou]', '-', 'the cat sat on the mat', flags=re.IGNORECASE)
'th- c-t s-t -n th- m-t'