为什么 re.search('\.', '.') 而不是 return None?
Why does re.search('\.', '.') not return None?
import re
我想检查字符串是否包含句号。我知道我能做到
>>> re.search(re.escape('.'), '.')
<re.Match object; span=(0, 1), match='.'>
或者,等价地,
>>> re.search('\.', '.')
<re.Match object; span=(0, 1), match='.'>
我也可以使用原始字符串
>>> re.search(r'\.', '.')
<re.Match object; span=(0, 1), match='.'>
但是为什么
>>> re.search('\.', '.')
<re.Match object; span=(0, 1), match='.'>
也工作? Python 是否在幕后将其隐式转换为原始字符串?
Does Python implicitly convert it to a raw string under the hood or something?
\.
不是 valid escape sequence,因此 Python 隐含地假定一个实际的 \
字符(又名 \.
)并触发 DeprecationWarning
,但由于默认情况下它们是静音的,因此您只会获得“工作版本”。
如果启用 DeprecationWarning
s(技术上所有警告),会发生以下情况:
❯ python -q -Wd
>>> '\.'
<stdin>:1: DeprecationWarning: invalid escape sequence \.
'\.'
此外,FWIW“原始字符串”不是一种类型,它只是一种语法上的便利。 “原始”和“非原始”字符串都会产生字符串对象,它们只是改变了字符串文字的解析方式。
import re
我想检查字符串是否包含句号。我知道我能做到
>>> re.search(re.escape('.'), '.')
<re.Match object; span=(0, 1), match='.'>
或者,等价地,
>>> re.search('\.', '.')
<re.Match object; span=(0, 1), match='.'>
我也可以使用原始字符串
>>> re.search(r'\.', '.')
<re.Match object; span=(0, 1), match='.'>
但是为什么
>>> re.search('\.', '.')
<re.Match object; span=(0, 1), match='.'>
也工作? Python 是否在幕后将其隐式转换为原始字符串?
Does Python implicitly convert it to a raw string under the hood or something?
\.
不是 valid escape sequence,因此 Python 隐含地假定一个实际的 \
字符(又名 \.
)并触发 DeprecationWarning
,但由于默认情况下它们是静音的,因此您只会获得“工作版本”。
如果启用 DeprecationWarning
s(技术上所有警告),会发生以下情况:
❯ python -q -Wd
>>> '\.'
<stdin>:1: DeprecationWarning: invalid escape sequence \.
'\.'
此外,FWIW“原始字符串”不是一种类型,它只是一种语法上的便利。 “原始”和“非原始”字符串都会产生字符串对象,它们只是改变了字符串文字的解析方式。