简体   繁体   中英

How does python compare strings and integers

In the following code below this is a simple algorithm written to sort the elements.My question is that how are strings are compared internally and how the interpreter knows that these strings are to be placed after the integers

a=[22, 66, 54, 11, 16, 2, 5, 'b', 'a', 3, 2, 1] 
>>> for i in range(len(a)-1):
...    for j in range(len(a)-i-1):
...       if a[j] > a[j+1]:
...          a[j],a[j+1]=a[j+1],a[j]
...
>>> print a
[1, 2, 2, 3, 5, 11, 16, 22, 54, 66, 'a', 'b']

In 2.x, if the two objects cannot be coerced to a common type then it compares the class names. "str" > "int", so they come after.

In 3.x, if the two objects cannot be coerced to a common type then an exception is raised.

Arbitrarily.

Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result). Furthermore, some types (for example, file objects) support only a degenerate notion of comparison where any two objects of that type are unequal. Again, such objects are ordered arbitrarily but consistently . The <, <=, > and >= operators will raise a TypeError exception when any operand is a complex number.

From Built-In Types (Python.org)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM