Bob Napkin
Bob Napkin

Reputation: 566

String sorting without converting to array

I'm solving a problem where I need to specific sort, that I wrote in my function MyFn, but result of sorted in python is a list. Is it possible to return string without using join? sorted(s, key=MyFn)

Upvotes: 0

Views: 603

Answers (2)

GingerPlusPlus
GingerPlusPlus

Reputation: 5616

Is it possible to return string without using join?

Yes, it is possible, but it's slow:

src = ['a', 'b', 'c']
dest = ''

for c in src:
    dest += src

print(dest)

Or, with functools.reduce:

from functools import reduce
src = ['a', 'b', 'c']
dest = reduce(str.__add__, src)
print(dest)

Upvotes: 0

Delgan
Delgan

Reputation: 19627

This is not possible because sorted() is designed to return a list.

However, you can use .join() to convert it back to a string.

s_list = sorted(s, key=MyFn)
s_str = "".join(s_list)

If you can not use .join(), there is another way but this is a bit tricky and I highly not recommand it. You can use repr() to convert your list to a string, and then thanks to slicing, you can get the letters from this list:

s_str = repr(sorted(s, key=MyFn))[2::5]

As representation of a list of chars is something like ['s', 't', 'r', 'i', 'n', 'g'], this should work.

Upvotes: 3

Related Questions