Python判断字符串相等

简介: Python判断字符串相等

Python判断字符串相等


Python中,判断两个字符串是否相等或一样,可以使用 ==或者 is来判断;判断不一样可以使用 is not

>>> a = 'abcd'
>>> b = 'abcd'
>>> a == b
True
>>> a is b
True
>>> c = 'aaaa'
>>> a is c
False
>>> a is not c
True
>>>

使用注意事项:

  1. 有时候两个字符串打印出来看着一样,但是判断却是False?如果两个字符串末尾有其他符号,比如回车\n,print的时候无法发现的,所以需要strip:
a.strip() == b


有时候==判断是 True ,is 判断却是 False?这是因为两个字符串来自不同的内存块,内存地址不一样。id() 函数用于获取对象的内存地址。(ob1 is ob2) 等价于 (id(ob1) == id(ob2)) ;id()函数可以获得对象的内存地址,如果两个对象的内存地址是一样的,那么这两个对象肯定是一个对象,和is是等价的.

>>> af = 'af.txt'
>>> a = af.split(".")[0]
>>> a
'af'
>>> b = 'af'
>>> a == b
True
>>> a is b
False
>>> id(a) == id(b)
False


目录
相关文章
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
330 100
|
3月前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
446 99
|
3月前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
3月前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
3月前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
3月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
4月前
|
索引 Python
python 字符串的所有基础知识
python 字符串的所有基础知识
341 0
|
4月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
290 92
|
4月前
|
Python
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。

推荐镜像

更多