0

Python begginer | need help in understanding key in 'sorted' function

While practicing string section of Python. I'm stuck at below code # to sort a string lexicographically. def lexicographi_sort(s): return sorted(sorted(s), key=str.upper) As per my understanding 'str.upper()' returns uppercase value of a string. Could someone please help me understand how "key=str.upper" works here?

25th Aug 2017, 3:27 PM
K Negi
K Negi - avatar
5 odpowiedzi
+ 7
The 'key' argument can even be a very advanced formula. Check it out: https://code.sololearn.com/cJqu6Q00Gidt/?ref=app
25th Aug 2017, 7:08 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 4
@K Negi Because we might receive different input, sometimes the IP address part will be three-digit, sometimes two, sometimes one. The two- and one-digit ones will sometimes be preceded with 0 and sometimes not. So we add the double zero just in case. Then, when we take "the last three" digits, they will always be sortable (will contain preceding zeros when needed). EDIT: The above is valid if you asked for the technical details. If the question was regarding *why* we do that in the first place - well, we'd like to sort it in the ascending order with preserving all the rules applying to IP address masks. So that: 100.233.12.34 is *after* 20.34.98.3 If we just took a string representation of the whole IP address, that would not happen.
3rd Sep 2017, 4:56 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 1
@Kuba Siekierzyński Thanks for sharing the code. Could you please help me understand the part "[-3::]". why do we need to do this slicing ? ''.join(('00'+j.split('.')[i])[-3::]
3rd Sep 2017, 2:56 PM
K Negi
K Negi - avatar
- 1
suppose a="sololearn" a[-3::] = "arn"
3rd Sep 2017, 3:20 PM
sayan chandra
sayan chandra - avatar