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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • vue取消eslint规范_vue运行eslint报错

    vue取消eslint规范_vue运行eslint报错关闭eslint代码规范检查

    2022年10月8日
    5
  • Exchange 2010 重建OWA报错

    Exchange 2010 重建OWA报错

    2021年8月15日
    47
  • 转:CCriticalSection「建议收藏」

    转:CCriticalSection「建议收藏」类CCriticalSection的对象表示一个“临界区”,它是一个用于同步的对象,同一时刻只允许一个线程存取资源或代码区。临界区在控制一次只能有一个线程修改数据或其它的控制资源时非常有用。例如在链表中增加一个节点就中允许一次一个线程进行。通过使用CCriticalSection对象来控制链表,就可以达到这个目的。在运行性能比较重要而且资源不会跨进程使用时,建议采用临界区代替信号灯。有关在MF…

    2022年7月20日
    15
  • Web前端和Web后端的区分「建议收藏」

    一、绪论1、前台:呈现给用户的视觉和基本的操作。后台:用户浏览网页时,我们看不见的后台数据跑动。后台包括前端、后端。前端:对应我们写的html、css、javascript等网页语言作用在前端网页。后端:对应jsp、javaBean、dao层、action层和service层的业务逻辑代码。(包括数据库)为什么jsp是后端呢?主要是jsp的运行原理是在tomcat服务器运…

    2022年4月18日
    47
  • 使用srvany.exe将任何程序作为Windows服务运行[通俗易懂]

    使用srvany.exe将任何程序作为Windows服务运行[通俗易懂]srvany.exe是什么?srvany.exe是MicrosoftWindowsResourceKits工具集的一个实用的小工具,用于将任何EXE程序作为Windows服务运行。也就是说srvany只是其注册程序的服务外壳,这个特性对于我们来说非常实用,我们可以通过它让我们的程序以SYSTEM账户启动,或者实现随机器启动而自启动,也可以隐藏不必要的窗口,比如说控制台窗口等等。如何获取

    2022年6月11日
    35
  • Spring中的AOP以及切入点表达式和各种通知

    Spring中的AOP以及切入点表达式和各种通知上篇讲了动态代理:Java中动态代理的两种方式JDK动态代理和cglib动态代理以及区别我们用上篇的做法去实现目标方法的增强,实现代码的解耦,是没有问题的,但是还是需要自己去生成代理对象,自己手写拦截器,在拦截器里自己手动的去把要增强的内容和目标方法结合起来,这用起来还是有点繁琐,有更好的解决方案吗?答案是:有的!那就是Spring的AOP,这才是咱们最终想引出来的重点!有了Sprin…

    2022年7月27日
    10

发表回复

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

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