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面向对象三大特性「建议收藏」

    java面向对象三大特性「建议收藏」一、面向对象的概念面向对象是一种符合人类思维习惯的编程思想。现实生活中存在各种形态不同的事物,这些事物之间存在着各种各样的联系。在程序中使用对象来映射现实中的事物使用对象的关系来描述事物之间的联系,这种思想就是面向对象。提到面向对象,自然会想到面向过程,面向过程就是分析解决问题所需要的步骤,然后用函数把这些步骤一一实现,使用的时候一个一个依次调用就可以了。面向对象则是把解决的问题按照一定规则划分为多个独立的对象,然后通过调用对象的方法来解决问题。当然,一个应用程序会包含多个对象,通过多个对象的相互配合来

    2022年7月8日
    19
  • linux platform driver register

    linux platform driver registerPlatformDevicesandDrivers~~~~~~~~~~~~~~~~~~~~~~~~~~~~Seeforthedrivermodelinterfacetotheplatformbus: platform_device,andplatform_driver. Thispseudo-busisusedtoconnectdevice

    2022年7月26日
    13
  • windows添加路由命令route add_windows添加路由命令route add

    windows添加路由命令route add_windows添加路由命令route addLinux下routeadd命令添加路由列表

    2022年8月11日
    5
  • 关于知行英语网 AfterClass「建议收藏」

    关于知行英语网 AfterClass「建议收藏」今天听以前一直听的《yellow》,一个MM边解析边放歌,发现它来自知行英语。于是到网上搜了下,发现还不错!http://www.24en.com/coop/afterclass/news/2006

    2022年7月2日
    30
  • pycharm 格式化代码[通俗易懂]

    pycharm 格式化代码[通俗易懂]有时候将空格键和tab键混用,在windows上没什么事情,但是如果移动到linux就会有问题,所以我们在移动到linux上之前要先格式化一下代码:ctrl+alt+L可以格式化,但是和锁屏快捷键冲突。 也可以,先选中代码,使用快捷键 ctrl+alt+i 。 …

    2022年8月25日
    7
  • Spring笔记(1)

    Spring笔记(1)

    2021年11月11日
    40

发表回复

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

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