python字符串判断相等总结

2022-10-17 09:47:21

判断字符串相等使用==,不使用is和cmp()函数

cmp() 函数则是相当于 <,==,> 但是在 Python3 中,cmp() 函数被移除了,所以我以后还是避免少用这个函数。

#-*-conding:utf-8-*-
i='新闻';
m=input();if i==m:print('yes');else:print('no');input();
if second_company_name== u'中外运长航'or second_company_name== u'长航集团':print(u'忽略中外运长航和长航集团的子公司')continue

在 if 判断语句中非常有用呐!

#!/usr/bin/python# Filename: if.py
  
number=23
guess=int(raw_input('Enter an integer : '))if guess== number:print'Congratulations, you guessed it.'# New block starts hereprint"(but you do not win any prizes!)"# New block ends hereelif guess< number:print'No, it is a little higher than that'# Another block# You can do whatever you want in a block ...else:print'No, it is a little lower than that'# you must have guess > number to reach hereprint'Done'# This last statement is always executed, after the if statement is executed```## strip 去掉字符串其他符号
str1= str1.strip()#去掉字符串中其他符号包括换行符等等
str2= str2.strip()if str2== str1:...#自己的代码## == 与 is的区别
python中,使用==来比较两个**对象的值**是否相等,而java 则使用== 比较两个**对象**是否是同一对象
譬如,java中比较字符串,一般使用equal 方法,来比较两个对象的值是否相等,而不使用==

相比较的,python 使用**is** 来比较两个对象是否是同一对象。is 用来判断是否是同一个对象,is 是种很特殊的语法,你在其它的语言应该不会见到这样的用法。
官方文档解释:

```python
The operators ``is``and ``isnot`` testforobject identity: ``xis
y``is trueifand onlyif*x*and*y* are the sameobject. ``xisnot y`` yields the inverse truth value.cmp(...)cmp(x, y)-> integer
  
 Return negativeif x<y, zeroif x==y, positiveif x>y.

注意:内容相同的字符串实际上是同一个对象

>>> a='abc'>>> b='abc'>>> ais bTrue>>>id(a)==id(b)True>>>>```

(Java 中直接赋值的字符串也可用== 来判断,但是使用 new 实例化的对象则需要使用equals(String s) 来判断)## 判断数字相等不要用 is 操作符

```python>>> a=256>>> b=256>>>id(a)9987148>>>id(b)9987148>>> a=257>>> b=257>>>id(a)11662816>>>id(b)11662828

为什么两次 is 返回的是不同结果?不是应该都是 true 吗?
因为 string pooling (或叫intern)。 is 相等代表两个对象的 id 相同(从底层来看的话,可以看作引用同一块内存区域)。 至于为什么 “ABC” 被 intern 了而 “a bc” 没有,这是 Python 解析器实现决定的,可能会变。

== 用来判断两个对象的值是否相等(跟 Java 不同,Java 中 == 用来判断是否是同一个对象)。
今天我用 == 来判断两个 IP 地址 字符串是否相同。

  • 作者:银灯玉箫
  • 原文链接:https://blog.csdn.net/lilele12211104/article/details/103007698
    更新时间:2022-10-17 09:47:21