Python 如何剥离字符串忽略大小写?
我试图从Python 如何剥离字符串忽略大小写?,python,Python,我试图从error变量中去掉“error:”一词,我想去掉error:对于所有情况,我该怎么做 error = "ERROR:device not found" #error = "error:device not found" #error = "Error:device not found" print error.strip('error:') re模块可能是您的最佳选择: re.sub('^error:', '', 'ERROR: device not found', flags=re
error
变量中去掉“error:”一词,我想去掉error:对于所有情况,我该怎么做
error = "ERROR:device not found"
#error = "error:device not found"
#error = "Error:device not found"
print error.strip('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:device not found"
现在,如果您想从中删除错误,只需删除字符串的前6个条目(如果您还想删除:)即可。像
error[6:]
其中:
device not found
此命令仅将条目6带到字符串的末尾。
希望这对你有帮助。确保只有在字符串开头出现错误时,此操作才有效。您可以使用正则表达式:
import re
error = "Error: this is an error: null"
print re.sub(r'^error:',"",error,count=1,flags=re.I).strip()
结果:
this is an error: null
解释
pattern
是一个正则表达式,这里我们使用前缀为r
的标准字符串来指定它是一个正则表达式
replacement
是要替换匹配项的内容,是要删除的空字符串
inputString
是要搜索的字符串,用于显示错误消息
count
要替换的事件数,在开始时仅替换一个
flags
:re.I
或re.IGNORECASE
匹配“ERROR”、“ERROR”和“ERROR”。strip
的工作方式与您想象的不一样,即使使用正确的大小写,您的示例也可能产生错误的结果。@markransem-如何去除错误:不考虑大小写?错误:
可以在string@JeffShort您需要将re.sub
的结果分配回error
@JeffShort,然后清除^
。
re.sub(pattern, replacement, inuputString, count=0, flags=0)