0

Please tell me why python choose this:

print(max("NEW new"))

OUTPUT: w

Had i understood correctly: lowercase in python on the first place, on the second place uppercase?

Thanks!

RjDeVera
  • 41
  • 1
  • 6
  • Quote from python doc: `If one positional argument is provided, iterable must be a non-empty iterable (such as a non-empty string, tuple or list). The largest item in the iterable is returned. If two or more positional arguments are provided, the largest of the positional arguments is returned.` – Haifeng Zhang Nov 14 '19 at 19:27
  • Lookup the ASCII values of the characters! – Klaus D. Nov 14 '19 at 19:27
  • The characters are evaluated according to ascii score and the max is taken... – StupidWolf Nov 14 '19 at 19:29
  • 1
    Note that all the answers here which mention ASCII are plain wrong: `max` will get a iterator from the unicode string, which yields unicode code points. The comparison is done code-point by code-point using the code-value. This just happens to be the byte value for pure-ASCII strings. But the "ASCII-answers" are nonsensical for `max("ϓΞφ")`. – user2722968 Nov 14 '19 at 20:34

3 Answers3

3

max will compare the ASCII value of each character in the string. You can see for yourself what they are by trying out ord('N') or ord(' ') or ord('w')

here is the result from python interpreter

>>> string = "NEW new"
>>> for s in string:
...     print(s , "--", ord(s))
... 
N -- 78
E -- 69
W -- 87
  -- 32
n -- 110
e -- 101
w -- 119
>>> 
physicist
  • 844
  • 1
  • 12
  • 24
0

This is just part of Python's definition for > on strings. It does lexicographic comparison with all lowercase letters coming after all uppercase letters. This is a result of the ordering of ASCII.

Since a string is an interable of characters, and max() goes through its iterable argument one by one and returns the one that compares > all the others, 'w' is the result.

Personman
  • 2,324
  • 1
  • 16
  • 27
0

in the ascii code lower case letters have a higher code (I.E come later in the table) then upper case letters. you can see this by printing the ascii code for each letter

for letter in "NEW new":
    print(f'{letter} : {ord(letter)}')

OUTPUT

N : 78
E : 69
W : 87
  : 32
n : 110
e : 101
w : 119

as you can see lower case w has the highest (max) value.

Chris Doyle
  • 10,703
  • 2
  • 23
  • 42