Python3中判断字符串是否相等的四种错误做法及正确方法求指点
htmlfile = open('D:/test.htm','rb')
htmlhandle = htmlfile.read()
soup = BeautifulSoup(htmlhandle, 'lxml')
table = soup.select('tr > td')
for tr in table:
infostr = re.findall(‘stream="adfs-(\d+)’,tr.prettify())
#做法 1
if (infostr.str() in “1776”):
print(infostr.str())
#做法 2
import operator
if (operator.eq(infostr.__str__(),"1776"))
print(infostr.__str__())
#做法 3,这个应该是 python2 的时候能用起来,python3 应该不行了吧?
if (infostr.__str__() == "1776")
print(infostr.__str__())
#做法 4,把 1776 强制指定为字符串变量,结果还是不行
import operator
if (operator.eq(infostr.__str__(),"1776"))
print(infostr.__str__())
想通过正则,判断截取出来的字符,是不是文本 1776 这个字符串?
已试过:
for tr in table:
print tr
确定 tr 是已经获取到字符串的了。。。。
求问正确的做法应该是?
Python3中判断字符串是否相等的四种错误做法及正确方法求指点
infostr 是一个列表呀
帖子标题里提到的“四种错误做法”具体是啥我不太确定,不过判断字符串相等这事儿,在Python3里真没那么多坑。最核心的就一点:直接用 == 操作符。这是最标准、最不会出错的方法。
str1 = "Hello"
str2 = "Hello"
str3 = "hello"
# 正确做法:使用 ==
print(str1 == str2) # 输出: True
print(str1 == str3) # 输出: False
# 判断不相等就用 !=
print(str1 != str3) # 输出: True
那些所谓的“错误做法”,我猜可能是下面这些新手容易迷糊的地方:
-
用
is来判断内容相等:is比较的是两个变量是不是指向内存里的同一个对象(身份标识),不是比较内容是否相同。对于短字符串(由于Python的驻留机制),可能碰巧为True,但这绝对不可靠。a = "hello" b = "hello" print(a is b) # 可能输出 True,但这是实现细节,不要依赖! c = "hello world!" d = "hello world!" print(c is d) # 很可能输出 False记住:比较内容,永远用
==;检查是不是同一个对象,才用is。 -
忽略大小写:如果想忽略大小写比较,应该先将字符串统一转为全大写或全小写,再用
==。str1 = "Python" str2 = "python" print(str1 == str2) # False print(str1.lower() == str2.lower()) # True -
处理用户输入时忘了去除空白符:输入常带空格或换行,直接比较会失败。
user_input = input("请输入'yes': ") # 用户输入了 " yes " if user_input == "yes": # 会失败 print("匹配成功") # 正确做法:先去除空白 if user_input.strip() == "yes": print("匹配成功") -
编码问题(较旧版本或特定场景):在Python 3中,字符串默认是Unicode,通常没问题。但在处理从文件或网络来的字节串(
bytes)时,需要先正确解码(.decode())为字符串(str)再比较,或者用==直接比较字节串。b = b"hello" # 字节串 s = "hello" # 字符串 # print(b == s) # 这会报错 TypeError print(b.decode('utf-8') == s) # True, 先解码 # 或者,直接比较字节串与字节串 b2 = "hello".encode('utf-8') print(b == b2) # True
总结:无脑用 == 和 != 就行,注意好大小写和输入清洗这些实际细节。
如 #1 说的.
re.findall 返回的是一个 list
,我真是傻了。。。意识到自己的错误,不胜感谢!!!
而且为啥要手动调用.__str__不应该用 str()的么

