熊猫替换和不区分大小写

熊猫替换和不区分大小写,第1张

熊猫替换和不区分大小写

case
参数实际上是一种方便的选择
flags=re.IGNORECASE
。如果替换不是基于正则表达式的,则与替换无关。

因此,当时

regex=True
,这些是您可能的选择:

pd.Series('Jr. eng').str.replace(r'jr.', 'jr', regex=True, case=False)# pd.Series('Jr. eng').str.replace(r'jr.', 'jr', case=False)0    jr engdtype: object

要么,

pd.Series('Jr. eng').str.replace(r'jr.', 'jr', regex=True, flags=re.IGNORECASE)# pd.Series('Jr. eng').str.replace(r'jr.', 'jr', flags=re.IGNORECASE)0    jr engdtype: object

您还可以通过将不区分大小写标志作为模式的一部分纳入,而变得厚脸皮并绕过两个关键字参数

?i
。看到

pd.Series('Jr. eng').str.replace(r'(?i)jr.', 'jr')0    jr engdtype: object

注意

您将需要

.
在正则表达式模式下转义句点,因为未转义的点是具有不同含义(匹配任何字符)的元字符。如果您想动态地转义模式中的元字符,可以使用
re.escape

有关标志和锚点的更多信息,请参阅文档和

re
HOWTO的本部分。


从源代码中可以很明显地看出,if忽略了“
case”参数

regex=False
。看到

# Check whether repl is valid (GH 13438, GH 15055)if not (is_string_like(repl) or callable(repl)):    raise TypeError("repl must be a string or callable")is_compiled_re = is_re(pat)if regex:    if is_compiled_re:        if (case is not None) or (flags != 0): raise ValueError("case and flags cannot be set"       " when pat is a compiled regex")    else:        # not a compiled regex        # set default case        if case is None: case = True        # add case flag, if provided        if case is False: flags |= re.IGNORECASE    if is_compiled_re or len(pat) > 1 or flags or callable(repl):        n = n if n >= 0 else 0        compiled = re.compile(pat, flags=flags)        f = lambda x: compiled.sub(repl=repl, string=x, count=n)    else:        f = lambda x: x.replace(pat, repl, n)

您可以看到

case
仅在
if
语句内部检查了参数。

IOW,唯一的方法是确保

regex=True
替换是基于正则表达式的。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/4917150.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-12
下一篇 2022-11-12

发表评论

登录后才能评论

评论列表(0条)

保存