如何忽略大小寫處理字串?

2024-04-25 22:33:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从error变量中去掉单词“error:”,我想去掉错误:全部案件?我怎么能做到呢?在

error = "ERROR:device not found"
#error = "error:device not found"
#error = "Error:device not found"
print error.strip('error:')

Tags: device错误noterror单词stripprint案件
3条回答

可以使用正则表达式:

import re
error = "Error: this is an error: null"
print re.sub(r'^error:',"",error,count=1,flags=re.I).strip()

结果:

^{pr2}$

说明

re.sub(pattern, replacement, inuputString, count=0, flags=0)

pattern是一个正则表达式,这里我们使用一个前缀为r的标准字符串来指定它是一个正则表达式。在

replacement是您想要用来代替匹配的内容,一个要删除的空字符串。在

inputString是您要搜索的字符串,您的错误消息。在

count要替换的发生次数,仅在开始时替换一个。在

flagsre.I或{}以匹配“ERROR”、“ERROR”和“ERROR”。在

re模块可能是您的最佳选择:

re.sub('^error:', '', 'ERROR: device not found', flags=re.IGNORECASE)

# '^error:' means the start of the string is error:
# '' means replace it with nothing
# 'ERROR: device not found' is your error string
# flags=re.IGNORECASE means this is a case insensitive search.

# In your case it would probably be this:
re.sub('^error:', '', error, flags=re.IGNORECASE)

这将删除字符串开头的ERROR:的所有变体。在

您有以下变量:

error = "ERROR:device not found"

现在,如果您想从中删除错误,只需删除字符串的前6个条目(如果您还想删除:)。像

^{pr2}$

它给出了:

device not found

这个命令只将条目6带到:字符串的末尾。 希望这对你有帮助。当然,只有当错误出现在字符串的开头时,这才有效

相关问题 更多 >