re 模块错误 error: bad character range

简介: 下午,看到堆栈的内容。于是上机实验了一番 >>> bds = '10+6/5-4*2' # 数学运算表达式   想用 findall 把运算符号提取出来 >>> import re >>> m = re.

 

下午,看到堆栈的内容。于是上机实验了一番

>>> bds = '10+6/5-4*2' # 数学运算表达式

 

想用 findall 把运算符号提取出来

>>> import re
>>> m = re.findall(r'[+-*/]', bds) # 习惯性地按加减乘除顺序排列:'[+-*/]'

 

可是报错: bad character range

>>> 
... ... 
... ... error: bad character range

错误的字符域?这是什么鬼?会不会跟字符排列顺序有关?

 

好吧,先看看这四个字符的 ascii 码:

>>> print([ord(x) for x in '+-*/'])
 [43, 45, 42, 47]

哦,其中星号 '*' 的码值 42 最小。

 

死马当活马医,把原来的 '+-*/' 按码值调整为 '*+-/' ,看看又如何:

>>> m = re.findall(r'[*+-/]', bds) # 按ASCII码值调整顺序为:'[*+-/]'
>>> m
 ['+', '/', '-', '*']

哇,终于搞定!!

 

总结:

一个猜想:re模块搜查单字符,其字符集合必须按其ASCII值(或者说编码值)由小到大排列,否则报错: error: bad character range

 

目录
相关文章
|
4月前
|
开发者 Python
【Python】已解决:TypeError: __init__() got an unexpected keyword argument ‘port’
【Python】已解决:TypeError: __init__() got an unexpected keyword argument ‘port’
537 0
【Python】已解决:TypeError: __init__() got an unexpected keyword argument ‘port’
|
4月前
|
机器学习/深度学习 Python
【Python】已解决TypeError: init() got an unexpected keyword argument ‘threshold’
【Python】已解决TypeError: init() got an unexpected keyword argument ‘threshold’
123 0
|
4月前
|
JSON Java 数据格式
JSON parse error: Unexpected character (‘t‘ (code 116)): was expecting double-quote to start field n
JSON parse error: Unexpected character (‘t‘ (code 116)): was expecting double-quote to start field n
|
6月前
|
Python
完美解决丨File “invalid.py“, line 1 print(`Hello World!`) ^ SyntaxError: invalid syntax
完美解决丨File “invalid.py“, line 1 print(`Hello World!`) ^ SyntaxError: invalid syntax
|
JavaScript
Invalid char (/) found at index (10) in sheet name异常原因|导出excel出现Invalid char (/) found at index (10)
Invalid char (/) found at index (10) in sheet name异常原因|导出excel出现Invalid char (/) found at index (10)
|
应用服务中间件
Tomcat请求特殊字符参数问题:Invalid character found in the request target. The valid characters are defined in
Tomcat请求特殊字符参数问题:Invalid character found in the request target. The valid characters are defined in
695 0
Tomcat请求特殊字符参数问题:Invalid character found in the request target. The valid characters are defined in
|
SQL 并行计算 数据库连接
ArcSWAT报错:Error Number :-2147467259; 对 COM 组件的调用返回了错误 HRESULT E_FAIL
ArcSWAT报错:Error Number :-2147467259; 对 COM 组件的调用返回了错误 HRESULT E_FAIL
|
关系型数据库 MySQL Linux
SQLSTATE[HY000]: General error: 1364 Field ‘xxx’ doesn't have a default value 解决办法
SQLSTATE[HY000]: General error: 1364 Field ‘xxx’ doesn't have a default value 解决办法
1500 0
error C2041: illegal digit ‘9‘ for base ‘8‘ | error C2059: syntax error: ‘bad suffix on number‘
error C2041: illegal digit ‘9‘ for base ‘8‘ | error C2059: syntax error: ‘bad suffix on number‘
139 0
成功解决absl.flags._exceptions.UnrecognizedFlagError: Unknown command line flag 'data_format'
成功解决absl.flags._exceptions.UnrecognizedFlagError: Unknown command line flag 'data_format'