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

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

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

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • power函数_power pivot函数

    power函数_power pivot函数#include<stdio.h>#include<math.h>//power函数doublepower(doublex,doubley);intmain(){ do

  • c++ 11 list转set「建议收藏」

    c++ 11 list转set「建议收藏」list<int> li; for(inti=0;i<100;i++){ li.push_back(i); } for(inti=0;i<100;i++){ li.push_back(i); } unordered_set<int> uset(li.begin(),li.end());//用list去初始化s…

  • EL表达式语言_el表达式的语法格式

    EL表达式语言_el表达式的语法格式EL表达式语言1.El简介EL(ExpressionLanguage,表达式语言)是一-种简单的语言,可以方便地访问和处理应用程序数据,而无需使用JSP脚本元素(Scriptlet)或JSP表达式。EL最初是在标准标签库JSTL(JavaServerPageStandardTagLibrary)1.0中定义,从JSTL1.1开始,SUN公司将EL…

  • JMM 详解_jmm是什么意思

    JMM 详解_jmm是什么意思多任务和高并发的内存交互多任务和高并发是衡量一台计算机处理器的能力重要指标之一。一般衡量一个服务器性能的高低好坏,使用每秒事务处理数(TransactionsPerSecond,TPS)这个指标比较能说明问题,它代表着一秒内服务器平均能响应的请求数,而TPS值与程序的并发能力有着非常密切的关系。物理机的并发问题与虚拟机中的情况有很多相似之处,物理机对并发的处理方案对于虚拟机的实现也有相

  • 产品配件类目税目分类_HS编码知识:汽车零部件怎么归类?[通俗易懂]

    产品配件类目税目分类_HS编码知识:汽车零部件怎么归类?[通俗易懂]本文以“汽车零部件”为例,介绍了如何对汽车零部件进行分类,找到合适的HS编码。据统计,每辆车约有一万个零件,涉及200多个税号,分布在进出口税号的不同章节。因此,汽车零部件的分类一直是一个大争议。可以说,汽车零部件的分类比较复杂。一、汽车零部件分类的规则与思路虽然“进出口关税”专门设置了87.08的汽车零部件税项,但实际工作中有很多汽车零部件不能归入87.08,如汽车发动机零件,共计500多个,不…

  • 带你深入了解 GitLab CI/CD 原理及流程

    点击上方“全栈程序员社区”,星标公众号 重磅干货,第一时间送达 作者:狂乱的贵公子 cnblogs.com/cjsblog/p/12256843.html GitLab CI/CD…

发表回复

您的电子邮箱地址不会被公开。

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