0
Str1=["Josephine","Joseph smith"]

Josephine should come first but due to space Joseph smith comes first.

vaultah
  • 44,105
  • 12
  • 114
  • 143
Paras Singh
  • 383
  • 1
  • 3
  • 11

3 Answers3

9

What you're describing is:

>>> Str1 = ['Josephine', 'Joseph smith']
>>> sorted(Str1)
['Joseph smith', 'Josephine']

You can provide a key to list.sort or sorted to make your string comparisons ignore whitespace:

>>> sorted(Str1, key=lambda x: ''.join(x.split()))
['Josephine', 'Joseph smith']
wildwilhelm
  • 4,809
  • 1
  • 19
  • 24
  • 1
    A rather convoluted way to remove whitespace, also will replace newline characters which may not be desired, why not just use `replace()`? – Chris_Rands Nov 23 '16 at 11:04
  • 1
    @Chris_Rands [whitespace](https://en.wikipedia.org/wiki/Whitespace_character) includes newlines (and tabs), and is what the question explicitly asks to be ignored in the title. – Zero Piraeus Nov 23 '16 at 11:06
  • @ZeroPiraeus Okay I agree – Chris_Rands Nov 23 '16 at 12:28
3

You pass in a sort key that replaces all space character with an empty string:

Str1.sort(key=lambda k: k.replace(' ', ''))
andres101
  • 67
  • 3
0

You can do it this way:

l = sorted(l, key=lambda x:x.replace(' ', ''))
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100