但对忽略的情况没有成功。我需要在一个给定的文本文件中找到一组词。我正在逐行阅读该文件。一行中的字可以是
曼蒂
,
敏迪
,
梦迪
,等等(我不想用
toupper
/
tolower
等)。
我正在寻找下面这个Perl代码的Python等价物。
if ($line=~/^Mandy Pande:/i)
10 个回答
0 人赞同
如果你不想使用str.lower()
,你可以使用一个正则表达式:
import re
if re.search('mandy', 'Mandy Pande', re.IGNORECASE):
# Is True
0 人赞同
还有一个帖子here.试着看一下这个。
BTW, you're looking for the .lower()
method:
string1 = "hi"
string2 = "HI"
if string1.lower() == string2.lower():
print "Equals!"
else:
print "Different!"
0 人赞同
人们可以在应用in
算子后使用str.casefold
to both strings.
str.casefold
是推荐使用的不区分大小写的比较方法。
Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.
大小写类似于小写,但更有侵略性,因为它的目的是去除一个字符串中的所有大小写区别。例如,德语小写字母'ß'相当于 "ss"。由于它已经是小写字母,lower()不会对'ß'做任何处理;casefold()将其转换为 "ss"。
大小写折叠算法在Unicode标准的3.13节中有描述。
New in version 3.3.
对于不区分大小写的子串搜索。
needle = "TEST"
haystack = "testing"
if needle.casefold() in haystack.casefold():
print('Found needle in haystack')
用于不区分大小写的字符串比较。
a = "test"
b = "TEST"
if a.casefold() == b.casefold():
print('a and b are equal, ignoring case')
0 人赞同
if haystackstr.lower().find(needlestr.lower()) != -1:
# True
0 人赞同
a = "MandY"
alow = a.lower()
if "mandy" in alow:
print "true"
0 人赞同
你也可以使用。s.lower() in str.lower()
0 人赞同
你可以将in
操作符与字符串的lower
方法结合使用。
if "mandy" in line.lower():
0 人赞同
import re
if re.search('(?i)Mandy Pande:', line):
0 人赞同
See this.
In [14]: re.match("mandy", "MaNdY", re.IGNORECASE)
Out[14]: <_sre.SRE_Match object at 0x23a08b8>
0 人赞同
如果是大熊猫系列,你可以提到case=False在str.contains中
data['Column_name'].str.contains('abcd', case=False)
或者,如果只是两个字符串的比较,请尝试以下其他方法
你可以使用casefold()方法。casefold()方法在比较的时候会忽略案例。
firstString = "Hi EVERYONE"
secondString = "Hi everyone"
if firstString.casefold() == secondString.casefold():
print('The strings are equal.')
else: