栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

熊猫替换和不区分大小写

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

熊猫替换和不区分大小写

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
替换是基于正则表达式的。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/374711.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号