genuis genuis - 2 months ago 6
Python Question

Alphabetically order in python of a string

I understand there is sort() function, but it won't work for me here. I would like to order alphabetically a string like follows:

'S NOM V NOUN VERB'


It should be:

'NOM NOUN S VERB V'


How can I achieve that in python?

Edit:

I have tried:

''.join(sorted(m[i][j]))


But this returned with very changed output like
ABEILMNNNNOOPRSUVV
for example which doesn't make sense.

Answer

Try the following:

x = 'S  NOM  V  NOUN  VERB'
x = x.split()   # produces ['S', 'NOM', 'V', 'NOUN', 'VERB']
x = sorted(x)   # produces ['NOM', 'NOUN', 'S', 'V', 'VERB']
x = ' '.join(x) # produces 'NOM NOUN S V VERB'

You will have to use a custom sorting function if you want the order of V and VERB to be reversed (see the 'key' keyword for the sorted function).