How to sort list of String without considering Special characters and with case insensitive

MRAB python at mrabarnett.plus.com
Tue Nov 27 12:54:23 EST 2012


On 2012-11-27 17:31, san wrote:
> Please let me know how to sort the list of String in either ascending / descending order without considering special characters and case.
> ex: list1=['test1_two','testOne','testTwo','test_one']
> Applying the list.sort /sorted method results in sorted list ['test1_two', 'testOne', 'testTwo', 'test_one']
> but the without considering the special characters and case it should be
> ['testOne','test_one', 'test1_two','testTwo'] OR ['test_one','testOne','testTwo', 'test1_two' ]
>
> list.sort /sorted method sorts based on the ascii value of the characters but Please let me knwo how do i achieve my expected one
>
(I'm using Python 3.)

The .sort method accepts a 'key' argument, which lets you pass a
function that transforms the value being sorted before comparison:

 >>> def make_key(string):
	return string.replace('_', '').upper()

 >>> list1 = ['test1_two', 'testOne', 'testTwo', 'test_one']
 >>> list1.sort(key=make_key)
 >>> list1
['test1_two', 'testOne', 'test_one', 'testTwo']

I don't know how you define 'special'.

You could remove any characters which are special or keep any
characters which are not special, depending on how many characters are
defined as 'special':

from string import ascii_letters

# Sets are faster for this kind of thing.
ascii_letters = set(ascii_letters)

def make_key(string):
     return ''.join(c for c in string if c in ascii_letters).upper()

list1 = ['test1_two', 'testOne', 'testTwo', 'test_one']
list1.sort(key=make_key)

print(list1)

# Output is: ['testOne', 'test_one', 'test1_two', 'testTwo']




More information about the Python-list mailing list