Python字符串比较

Python字符串比较InthistutorialwearegoingtoseedifferentmethodsbywhichwecancomparestringsinPython.Wewillalsoseesometrickycaseswhenthepythonstringcomparisoncanfailandgoldenrulestoget…

大家好,又见面了,我是你们的朋友全栈君。

In this tutorial we are going to see different methods by which we can compare strings in Python. We will also see some tricky cases when the python string comparison can fail and golden rules to get string comparison always right.

在本教程中,我们将看到用于比较Python中字符串的不同方法。 我们还将看到一些棘手的情况,这时python字符串比较可能会失败,并且黄金规则总是可以正确进行字符串比较。

Python strings are Immutable. 

Python字符串是不可变的。

This means that once you have created a string then it cannot be modified, if you do modify it then it will create a new python string. Example below will explain the fact.

这意味着一旦创建了字符串,便无法对其进行修改,如果您进行了修改,则它将创建一个新的python字符串。 下面的示例将说明事实。

str1 = 'TheCrazyProgrammer'
str2 = 'TheCrazyProgrammer'
 
print(id(str1))  # Prints 54154496
print(id(str2))  # Prints 54154496
 
str1 += '.com'
 
print(id(str1))  # Prints 54154400

Here when we make change in str1 then the id of the string changes that confirms that a new string object is created. Now one more question remains i.e. why str1 and str2 have the same id ? 

在这里,当我们在str1中进行更改时,字符串的ID会更改,以确认创建了新的字符串对象。 现在还有一个问题,即为什么str1和str2具有相同的id?

That is because python do memory optimizations and similar string object are stored as only one object in memory. This is also the case with small python integers. 

这是因为python进行内存优化,并且类似的字符串对象仅作为一个对象存储在内存中。 小python整数也是如此。

Now getting to string comparison there are two different methods by which we can compare strings as below.

现在开始进行字符串比较,有两种不同的方法可以用来比较字符串,如下所示。

Python字符串比较 (Python String Comparison)

方法1:比较使用is运算符 (Method 1: Comparing Using is Operator)

is and is not operator is used to compare two strings as below:

is和not运算符用于比较两个字符串,如下所示:

str1 = 'TheCrazyProgrammer'
 
str2 = 'TheCrazyProgrammer'
 
if str1 is str2 :
    print("Strings are equal")  # Prints String are equal 
else :
    print("String are not equal")

The two strings to be compared are written on either side of the is operator and the comparison is made. is operator compares string based on the memory location of the string and not based on the value stored in the string. 

将要比较的两个字符串写在is运算符的任一侧,然后进行比较。 is运算符根据字符串的存储位置而不是基于字符串中存储的值来比较字符串。

Similarly to check if the two values are not equal the is not operator is used. 

类似地,检查两个值是否不相等,使用了 is not 运算符。

方法2:使用==运算符进行比较 (Method 2: Comparing Using == Operator)

The == operator is used to compare two strings based on the value stored in the strings. It’s use is similar to is operator.

==运算符用于根据字符串中存储的值比较两个字符串。 它的用法类似于is运算符。

str1 = 'TheCrazyProgrammer'
 
str2 = 'TheCrazyProgrammer'
 
if str1 == str2 :
    print("Strings are equal")  # Prints String are equal 
else :
    print("String are not equal")

Similarly to check if the two strings are not equal the != is used. 

类似地,检查两个字符串是否相等,使用 !=

Why the python string being immutable is important?

为什么python字符串不可更改很重要?

Even the python strings weren’t immutable then a comparison based on the memory location would not be possible and therefore is and is not operator cannot be used. 

即使python字符串也不是不可变的,那么基于内存位置的比较也是不可能的,因此不能使用,并且不能使用运算符。

Both of the comparison methods above are case sensitive i.e. ‘Cat’ and ‘cat’ are treated differently. Function below can be used to first convert the string in some particular case and then use them.

上面的两种比较方法都区分大小写,即“猫”和“猫”的区别对待。 下面的函数可用于在某些特定情况下首先转换字符串,然后再使用它们。

  • .lower() : makes the string lowercase 

    .lower():使字符串变为小写

  • .upper() : makes the string uppercase

    .upper():使字符串大写

So if both strings are first converted into a similar case and then checked then it would make the comparison case insensitive indirectly. Example below will make things more clear. 

因此,如果首先将两个字符串都转换为相似的大小写,然后再进行检查,则这将使比较大小写间接变得不敏感。 下面的示例将使事情更加清楚。

str1 = 'TheCrazyProgrammer'
 
str2 = 'tHecRazyprogrammer'
 
if str1 == str2 :
    print("Strings are equal")
else :
    print("String are not equal") # Prints String are not equal
 
if str1.upper() == str2.upper() :
    print("Strings are equal")   # Prints String are equal
else :
    print("String are not equal")

The golden line to remember whenever using the == and is operator is 

每当使用==和is运算符时要记住的金线是

== used to compare values and is used to compare identities.

==用于比较值,并用来比较的身份。

One more thing to remember here is:

这里要记住的一件事是:

if x is y is then x == y is true

如果 x 是 y , 则 x == y 是 true

It is easily understandable as x and y points to the same memory locations then they must have the same value at that memory location. But the converse is not true. Here is an example to support the same:

这很容易理解,因为x和y指向相同的存储位置,然后它们在该存储位置必须具有相同的值。 但是反过来是不正确的。 这是一个支持相同示例的示例:

a = {"a":1}
c = a.copy()
 
print(a is c)  # Prints False
print(a == c) # Prints True

In this example c is at a new memory location and that’s why a is c prints false.

在此示例中,c位于新的内存位置,这就是为什么a是c的结果为false的原因。

翻译自: https://www.thecrazyprogrammer.com/2019/11/python-string-comparison.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/150472.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • java resourcebundle_Java – Properties和ResourceBundle类学习「建议收藏」

    java resourcebundle_Java – Properties和ResourceBundle类学习「建议收藏」一、前言在项目的开发过程中,为了统一配置的管理,我们经常需要将一些配置信息根据环境的不同,配置在不同的properties中,然后从里面进行读取。而Properties类作为最基础也是最经常使用的类,通过本文我们来学习一下它的使用,然后再顺便学习下其他几种读取properties文件的方式。二、Properties和ResourceBundle类Properties表示一个持久的属性集,属性列表通…

    2022年7月12日
    15
  • javaweb权限管理简单实现_javaweb管理系统项目

    javaweb权限管理简单实现_javaweb管理系统项目推荐最新技术springboot版权限管理(java后台通用权限管理系统(springboot)),采用最新技术架构,功能强大!注:由于该项目比较老,所以没有采用maven管理,建议下载springboot权限管理系统,对学习和使用会更有帮助。springboot权限管理系统介绍地址:https://blog.csdn.net/zwx19921215/article/details/978……………

    2025年8月10日
    2
  • shell中的for循环用法详解

    shell中的for循环用法详解for命令:foriin的各种用法:foriin“file1”“file2”“file3”foriin/boot/*foriin/etc/*.confforiin$(seq-w10)–》等宽的01-10foriin{1..10}foriin$(ls)forIin$(

    2022年7月24日
    12
  • FM和FFM原理

    FM和FFM原理模型用途FM和FFM,分解机,是近几年出的新模型,主要应用于广告点击率预估(CTR),在特征稀疏的情况下,尤其表现出优秀的性能和效果,也数次在kaggle上的数据挖掘比赛中拿到较好的名次。FM原理特征编码时常用的one-hot编码,会导致特征非常稀疏(很多0值)。常用的特征组合方法是多项式模型,模型表达式如下: y(x)=w0+∑i=1nwixi+∑i=1n∑j=i+1nwijxixjy(x)=w…

    2022年5月20日
    50
  • 磁盘碎片整理软件评测

    磁盘碎片整理软件评测磁盘碎片整理软件评测选出适合你的软件 磁盘碎片整理软件大比评! 让系统自带碎片整理工具下岗,磁盘碎片整理软件大比评  硬盘在使用一段时间后,由于反复写入和删除文件,磁盘中的空闲扇区会分散到整个磁盘中不连续的物理位置上,从而使文件不能存在连续的扇区类。这样,再读写文件是就需要到不同的地方去读取,增加了磁头的来回移动,降低了磁盘的访问速度。硬盘就像屋子一

    2022年6月25日
    35
  • 电脑usb android上网,让你的Android手机通过USB共享电脑上网

    电脑usb android上网,让你的Android手机通过USB共享电脑上网转贴:来自http://www.diypda.com/viewthread.php?tid=150277首先这不是一篇关于如何让你的Android手机通过USB共享电脑上网(这里不讨论这样做的必要性)的教程,所以很多细节上被省略了。没有图。我们知道,可以使用USB将HTCHero连接至PC,“连接类型”选择“Internet共享(假设你的手机移动网络可用并是打开的),然后你的电脑就会…

    2025年7月20日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号