python字符串相等和ord()比较?

2024-04-25 19:07:40 发布

您现在位置:Python中文网/ 问答频道 /正文

 s1 = request.args.get('s1', '') 
 s2 = request.args.get('s2', '') 

    if '' not in [s1, s2]:
        if s1 == s2:
          if all(ord(c1) is ord(c2) for c1, c2 in zip(s1, s2)):
            msg = "first"
          else:
            msg += "second"
        else:
          msg = "thrid"
      else:
        msg = 'fourth'

我要这段代码打印“秒”。在

我试过这些输入 s1=“.0”和s2=“0.00”

有谁能简单解释一下“if all(ord(c1) is ord(c2) for c1, c2 in zip(s1, s2)):”到底是什么意思吗?在

我知道它与字符串相等以及比较字符串上的ord()有关,我想知道它们之间的区别。在

提前谢谢你的帮助。在

请原谅压痕。这里是Python初学者!在


Tags: inforgetifisrequestargsmsg
2条回答

在通俗的英语中,if all(ord(c1) is ord(c2) for c1, c2 in zip(s1, s2))表示ord(s1[i])和{}的所有值,范围从0到{}(其中c1和{},如果{}和{})的引用对于两个列表都是相同的

检查^{}文档。根据文件:

zip() returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The returned list is truncated in length to the length of the shortest argument sequence

例如:

>>> l1 = [1, 2 ,3]
>>> l2 = [7, 8, 9]
>>> zip(l1, l2)
[(1, 7), (2, 8), (3, 9)]

现在,[ord(c1) is ord(c2) for c1, c2 in zip(s1, s2)]将根据条件ord(c1) is ord(c2)返回{}值的元组列表,其中c1和{}是{}对,来自{}返回的上一个元组列表。在

现在是最后一部分。ifall()将返回True,如果上面提到的True/False值的列表[ ... ]将具有True的所有值。如果任何一项是Falseall()将返回值False

没有百分之百确定的方法让这段代码打印第二,因为实习是一个实现细节。在

CPython在[-5, 256]范围内实习整数

因此,您需要一个字符,当它被传递给ord时,它将返回值>;256。在

>>> s1 = "asdሴ"
>>> s2 = "asdሴ"
>>> s1 == s2
True
>>> all(ord(c1) is ord(c2) for c1, c2 in zip(s1, s2))
False

all(ord(c1) is ord(c2) for c1, c2 in zip(s1, s2))检查每个ord(c1)是否与ord(c2)具有相同的id。在

iddocumentation

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.

相关问题 更多 >