Why does Python's max() function place a low value on strings with a leading space? -



Why does Python's max() function place a low value on strings with a leading space? -

the quesion

i've noticed built-in max() function in python 2.7.6 seems place low "value" on strings leading space unless tell utilize len function key. why that?

example

consider snippet interactive interpreter:

>>> max(['abc', 'defgh']) 'defgh' >>> max(['abc', ' defgh']) 'abc' >>> max([' defgh']) ' defgh' >>> max(['abc', ' defgh'], key=len) ' defgh'

notes

i tried looking @ the source max(), , calls min_max(). on line 1370, case no key specified handled. there comment says "no key function; value item". don't know value associated string besides length, comment mean? also, why leading space impact magical value c code keying off of?

python doesn't "ignore" string @ - behavior exactly because python isn't ignoring anything.

rather space comes before letters , strings ordered lexicographical (case-sensitively!) or character-by-character. see ascii table relative ordering of space (space=32) , other characters in english language alphabet ("a"=97).

that is, " foo" < "foo" true, min(" foo", "foo") " foo" and, conversely, max(" foo", "foo") "foo". consequently, leads "z" < "a" beingness true may surprising..

if code wanted ignore space max(.., key = lambda i: i.strip()) used, perhaps case-normalization thrown in appropriate.

(the results adding key length function irrelevant in case, larger length max'er.)

python python-2.7 cpython

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -