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

Prasad, Ramit ramit.prasad at
Tue Nov 27 19:21:03 CET 2012

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

You can pass a key function into list.sort() and sorted(). This
allows you to customize the sorting. In the below examples
I use lambda but you can use a non-lambda function (if you need
more complexity).

Case insensitive searches are often done by converting the 
strings being compared into the same case. Here I turned
them all uppercase.

lst = ['test1_two', 'testOne', 'testTwo', 'test_one']
lst.sort(key=lambda x: x.upper())

This will filter non-alphanumeric characters. You may
be able to create and use a translation table instead.

lst.sort( key=lambda x: ''.join( c.upper() for c in x if c 
in string.letters+string.digits ) )


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at  

More information about the Python-list mailing list