gpt4 book ai didi

Python 重新编译 : unsupported operand type(s) for &: str and int

转载 作者:太空宇宙 更新时间:2023-11-04 08:05:09 24 4
gpt4 key购买 nike

我有以下代码:

import re
r = re.compile('^[0-9 ]{1,4}Ty', 'i')

我收到意外错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.4/re.py", line 219, in compile
return _compile(pattern, flags)
File "/usr/lib/python3.4/re.py", line 275, in _compile
bypass_cache = flags & DEBUG
TypeError: unsupported operand type(s) for &: 'str' and 'int'

如何解决?

最佳答案

'i' 不是有效的标志值,因为 all compilation flags used by re functions必须是整数(re 使用按位运算来操作标志)。

改用re.I(或re.IGNORECASE)

import re
r = re.compile('^[0-9 ]{1,4}Ty', re.I)

从技术上讲,您可以将标志指定为字符串,但在这种情况下,它们必须包含在模式中:

import re
r = re.compile('(?i)^[0-9 ]{1,4}Ty')

来自docs :

(?aiLmsux)

One or more letters from the set 'a', 'i', 'L', 'm', 's', 'u', 'x'. The group matches the empty string; the letters set the corresponding flags.

因此 (?i) 与将 re.I(或 re.IGNORECASE)传递给 compile< 具有相同的效果.

关于Python 重新编译 : unsupported operand type(s) for &: str and int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32505956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com